Passed
Push — dartcafe-patch-1 ( 76d9a9...bbc69b )
by René
02:30
created

PageController::searchForGroups()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 17
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
c 0
b 0
f 0
rs 9.2
cc 4
eloc 13
nc 8
nop 2
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\Date;
28
use OCA\Polls\Db\Event;
29
use OCA\Polls\Db\Notification;
30
use OCA\Polls\Db\Participation;
31
use OCA\Polls\Db\ParticipationText;
32
use OCA\Polls\Db\Text;
33
use OCA\Polls\Db\CommentMapper;
34
use OCA\Polls\Db\DateMapper;
35
use OCA\Polls\Db\EventMapper;
36
use OCA\Polls\Db\NotificationMapper;
37
use OCA\Polls\Db\ParticipationMapper;
38
use OCA\Polls\Db\ParticipationTextMapper;
39
use OCA\Polls\Db\TextMapper;
40
use OCP\AppFramework\Db\DoesNotExistException;
0 ignored issues
show
Bug introduced by
The type OCP\AppFramework\Db\DoesNotExistException 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...
41
use OCP\IUserManager;
0 ignored issues
show
Bug introduced by
The type OCP\IUserManager 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...
42
use OCP\IGroupManager;
0 ignored issues
show
Bug introduced by
The type OCP\IGroupManager 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...
43
use OCP\IAvatarManager;
0 ignored issues
show
Bug introduced by
The type OCP\IAvatarManager 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...
44
use OCP\ILogger;
0 ignored issues
show
Bug introduced by
The type OCP\ILogger 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...
45
use OCP\IL10N;
0 ignored issues
show
Bug introduced by
The type OCP\IL10N 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...
46
use OCP\IRequest;
0 ignored issues
show
Bug introduced by
The type OCP\IRequest 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...
47
use OCP\IURLGenerator;
0 ignored issues
show
Bug introduced by
The type OCP\IURLGenerator 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...
48
use OCP\Security\ISecureRandom;
0 ignored issues
show
Bug introduced by
The type OCP\Security\ISecureRandom 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...
49
use OCP\AppFramework\Http\TemplateResponse;
0 ignored issues
show
Bug introduced by
The type OCP\AppFramework\Http\TemplateResponse 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...
50
use OCP\AppFramework\Http\RedirectResponse;
0 ignored issues
show
Bug introduced by
The type OCP\AppFramework\Http\RedirectResponse 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...
51
use OCP\AppFramework\Http\JSONResponse;
0 ignored issues
show
Bug introduced by
The type OCP\AppFramework\Http\JSONResponse 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...
52
use OCP\AppFramework\Controller;
0 ignored issues
show
Bug introduced by
The type OCP\AppFramework\Controller 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...
53
use OCP\User;
0 ignored issues
show
Bug introduced by
The type OCP\User 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...
54
use OCP\Util;
0 ignored issues
show
Bug introduced by
The type OCP\Util 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...
55
56
class PageController extends Controller {
57
58
	private $userId;
59
	private $commentMapper;
60
	private $dateMapper;
61
	private $eventMapper;
62
	private $notificationMapper;
63
	private $participationMapper;
64
	private $participationTextMapper;
65
	private $textMapper;
66
	private $urlGenerator;
67
	private $manager;
68
	private $avatarManager;
69
	private $logger;
70
	private $trans;
71
	private $userMgr;
72
	private $groupManager;
73
74
	/**
75
	 * PageController constructor.
76
	 * @param $appName
77
	 * @param IRequest $request
78
	 * @param IUserManager $manager
79
	 * @param IGroupManager $groupManager
80
	 * @param IAvatarManager $avatarManager
81
	 * @param ILogger $logger
82
	 * @param IL10N $trans
83
	 * @param IURLGenerator $urlGenerator
84
	 * @param $userId
85
	 * @param CommentMapper $commentMapper
86
	 * @param DateMapper $dateMapper
87
	 * @param EventMapper $eventMapper
88
	 * @param NotificationMapper $notificationMapper
89
	 * @param ParticipationMapper $ParticipationMapper
90
	 * @param ParticipationTextMapper $ParticipationTextMapper
91
	 * @param TextMapper $textMapper
92
	 */
93
	public function __construct(
94
		$appName,
95
		IRequest $request,
96
		IUserManager $manager,
97
		IGroupManager $groupManager,
98
		IAvatarManager $avatarManager,
99
		ILogger $logger,
100
		IL10N $trans,
101
		IURLGenerator $urlGenerator,
102
		$userId,
103
		CommentMapper $commentMapper,
104
		DateMapper $dateMapper,
105
		EventMapper $eventMapper,
106
		NotificationMapper $notificationMapper,
107
		ParticipationMapper $ParticipationMapper,
108
		ParticipationTextMapper $ParticipationTextMapper,
109
		TextMapper $textMapper
110
	) {
111
		parent::__construct($appName, $request);
112
		$this->manager = $manager;
113
		$this->groupManager = $groupManager;
114
		$this->avatarManager = $avatarManager;
115
		$this->logger = $logger;
116
		$this->trans = $trans;
117
		$this->urlGenerator = $urlGenerator;
118
		$this->userId = $userId;
119
		$this->commentMapper = $commentMapper;
120
		$this->dateMapper = $dateMapper;
121
		$this->eventMapper = $eventMapper;
122
		$this->notificationMapper = $notificationMapper;
123
		$this->participationMapper = $ParticipationMapper;
124
		$this->participationTextMapper = $ParticipationTextMapper;
125
		$this->textMapper = $textMapper;
126
		$this->userMgr = \OC::$server->getUserManager();
127
	}
128
129
	/**
130
	 * @NoAdminRequired
131
	 * @NoCSRFRequired
132
	 */
133
	public function index() {
134
		$polls = $this->eventMapper->findAllForUserWithInfo($this->userId);
135
		$comments = $this->commentMapper->findDistinctByUser($this->userId);
136
		$partic = $this->participationMapper->findDistinctByUser($this->userId);
137
		$particText = $this->participationTextMapper->findDistinctByUser($this->userId);
138
		$response = new TemplateResponse('polls', 'main.tmpl', [
139
			'polls' => $polls,
140
			'comments' => $comments,
141
			'participations' => $partic,
142
			'participations_text' => $particText,
143
			'userId' => $this->userId,
144
			'userMgr' => $this->manager,
145
			'urlGenerator' => $this->urlGenerator
146
		]);
147
		if (class_exists('OCP\AppFramework\Http\ContentSecurityPolicy')) {
148
			$csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
0 ignored issues
show
Bug introduced by
The type OCP\AppFramework\Http\ContentSecurityPolicy 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...
149
			$response->setContentSecurityPolicy($csp);
150
		}
151
		return $response;
152
	}
153
154
	/**
155
	 * @param string $pollId
156
	 * @param string $from
157
	 */
158
	private function sendNotifications($pollId, $from) {
159
		$poll = $this->eventMapper->find($pollId);
0 ignored issues
show
Bug introduced by
$pollId of type string is incompatible with the type integer expected by parameter $id of OCA\Polls\Db\EventMapper::find(). ( Ignorable by Annotation )

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

159
		$poll = $this->eventMapper->find(/** @scrutinizer ignore-type */ $pollId);
Loading history...
160
		$notifications = $this->notificationMapper->findAllByPoll($pollId);
161
		foreach ($notifications as $notification) {
162
			if ($from === $notification->getUserId()) {
163
				continue;
164
			}
165
			$email = \OC::$server->getConfig()->getUserValue($notification->getUserId(), 'settings', 'email');
166
			if (strlen($email) === 0 || !isset($email)) {
167
				continue;
168
			}
169
			$url = \OC::$server->getURLGenerator()->getAbsoluteURL(\OC::$server->getURLGenerator()->linkToRoute('polls.page.goto_poll',
170
				array('hash' => $poll->getHash())));
171
172
			$recUser = $this->userMgr->get($notification->getUserId());
173
			$sendUser = $this->userMgr->get($from);
174
			$rec = "";
175
			if ($recUser !== null) {
176
				$rec = $recUser->getDisplayName();
177
			}
178
			if ($sendUser !== null) {
179
				$sender = $sendUser->getDisplayName();
180
			} else {
181
				$sender = $from;
182
			}
183
			$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>',
184
				array(
185
					$rec,
186
					$sender,
187
					$poll->getTitle(),
188
					$url
189
				));
190
191
			$msg .= "<br/><br/>";
192
193
			$toName = $this->userMgr->get($notification->getUserId())->getDisplayName();
194
			$subject = $this->trans->t('Polls App - New Comment');
195
			$fromAddress = Util::getDefaultEmailAddress('no-reply');
196
			$fromName = $this->trans->t("Polls App") . ' (' . $from . ')';
197
198
			try {
199
				$mailer = \OC::$server->getMailer();
200
				$message = $mailer->createMessage();
201
				$message->setSubject($subject);
202
				$message->setFrom(array($fromAddress => $fromName));
203
				$message->setTo(array($email => $toName));
204
				$message->setHtmlBody($msg);
205
				$mailer->send($message);
206
			} catch (\Exception $e) {
207
				$message = 'Error sending mail to: ' . $toName . ' (' . $email . ')';
208
				Util::writeLog("polls", $message, Util::ERROR);
209
			}
210
		}
211
	}
212
213
	/**
214
	 * @NoAdminRequired
215
	 * @NoCSRFRequired
216
	 * @PublicPage
217
	 * @param string $hash
218
	 * @return TemplateResponse
219
	 */
220
	public function gotoPoll($hash) {
221
		$poll = $this->eventMapper->findByHash($hash);
222
		if ($poll->getType() == '0') {
223
			$dates = $this->dateMapper->findByPoll($poll->getId());
224
			$votes = $this->participationMapper->findByPoll($poll->getId());
225
		} else {
226
			$dates = $this->textMapper->findByPoll($poll->getId());
227
			$votes = $this->participationTextMapper->findByPoll($poll->getId());
228
		}
229
		$comments = $this->commentMapper->findByPoll($poll->getId());
230
		try {
231
			$notification = $this->notificationMapper->findByUserAndPoll($poll->getId(), $this->userId);
232
		} catch (DoesNotExistException $e) {
233
			$notification = null;
234
		}
235
		if ($this->hasUserAccess($poll)) {
236
			return new TemplateResponse('polls', 'goto.tmpl', [
237
				'poll' => $poll,
238
				'dates' => $dates,
239
				'comments' => $comments,
240
				'votes' => $votes,
241
				'notification' => $notification,
242
				'userId' => $this->userId,
243
				'userMgr' => $this->manager,
244
				'urlGenerator' => $this->urlGenerator,
245
				'avatarManager' => $this->avatarManager
246
			]);
247
		} else {
248
			User::checkLoggedIn();
249
			return new TemplateResponse('polls', 'no.acc.tmpl', []);
250
		}
251
	}
252
253
	/**
254
	 * @NoAdminRequired
255
	 * @NoCSRFRequired
256
	 * @param string $pollId
257
	 * @return RedirectResponse
258
	 */
259
	public function deletePoll($pollId) {
260
		$poll = new Event();
261
		$poll->setId($pollId);
262
		$this->eventMapper->delete($poll);
263
		$this->textMapper->deleteByPoll($pollId);
264
		$this->dateMapper->deleteByPoll($pollId);
265
		$this->participationMapper->deleteByPoll($pollId);
266
		$this->participationTextMapper->deleteByPoll($pollId);
267
		$this->commentMapper->deleteByPoll($pollId);
268
		$url = $this->urlGenerator->linkToRoute('polls.page.index');
269
		return new RedirectResponse($url);
270
	}
271
272
	/**
273
	 * @NoAdminRequired
274
	 * @NoCSRFRequired
275
	 * @param string $hash
276
	 * @return TemplateResponse
277
	 */
278
	public function editPoll($hash) {
279
		$poll = $this->eventMapper->findByHash($hash);
280
		if ($this->userId !== $poll->getOwner()) {
281
			return new TemplateResponse('polls', 'no.create.tmpl');
282
		}
283
		if ($poll->getType() == '0') {
284
			$dates = $this->dateMapper->findByPoll($poll->getId());
285
		} else {
286
			$dates = $this->textMapper->findByPoll($poll->getId());
287
		}
288
		return new TemplateResponse('polls', 'create.tmpl', [
289
			'poll' => $poll,
290
			'dates' => $dates,
291
			'userId' => $this->userId,
292
			'userMgr' => $this->manager,
293
			'urlGenerator' => $this->urlGenerator
294
		]);
295
	}
296
297
	/**
298
	 * @NoAdminRequired
299
	 * @NoCSRFRequired
300
	 * @param $pollId
301
	 * @param $pollType
302
	 * @param $pollTitle
303
	 * @param $pollDesc
304
	 * @param $userId
305
	 * @param $chosenDates
306
	 * @param $expireTs
307
	 * @param $accessType
308
	 * @param $accessValues
309
	 * @param $isAnonymous
310
	 * @param $hideNames
311
	 * @return RedirectResponse
312
	 */
313
	public function updatePoll(
314
		$pollId,
315
		$pollType,
316
		$pollTitle,
317
		$pollDesc,
318
		$userId,
319
		$chosenDates,
320
		$expireTs,
321
		$accessType,
322
		$accessValues,
323
		$isAnonymous,
324
		$hideNames
325
	) {
326
		$event = $this->eventMapper->find($pollId);
327
		$event->setTitle(htmlspecialchars($pollTitle));
328
		$event->setDescription(htmlspecialchars($pollDesc));
329
		$event->setIsAnonymous($isAnonymous ? 1 : 0);
330
		$event->setFullAnonymous($isAnonymous && $hideNames ? 1 : 0);
331
332 View Code Duplication
		if ($accessType === 'select') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
333
			if (isset($accessValues)) {
334
				$accessValues = json_decode($accessValues);
335
				if ($accessValues !== null) {
336
					$groups = array();
337
					$users = array();
338
					if ($accessValues->groups !== null) {
339
						$groups = $accessValues->groups;
340
					}
341
					if ($accessValues->users !== null) {
342
						$users = $accessValues->users;
343
					}
344
					$accessType = '';
345
					foreach ($groups as $gid) {
346
						$accessType .= $gid . ';';
347
					}
348
					foreach ($users as $uid) {
349
						$accessType .= $uid . ';';
350
					}
351
				}
352
			}
353
		}
354
		$event->setAccess($accessType);
355
356
		$chosenDates = json_decode($chosenDates);
357
358
		$expire = null;
359 View Code Duplication
		if ($expireTs !== null && $expireTs !== '') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
360
			$expire = date('Y-m-d H:i:s', $expireTs + 60 * 60 * 24); //add one day, so it expires at the end of a day
361
		}
362
		$event->setExpire($expire);
0 ignored issues
show
Bug introduced by
It seems like $expire can also be of type string; however, parameter $value of OCA\Polls\Db\Event::setExpire() does only seem to accept OCA\Polls\Db\timestamp, maybe add an additional type check? ( Ignorable by Annotation )

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

362
		$event->setExpire(/** @scrutinizer ignore-type */ $expire);
Loading history...
363
364
		$this->dateMapper->deleteByPoll($pollId);
365
		$this->textMapper->deleteByPoll($pollId);
366
		if ($pollType === 'event') {
367
			$event->setType(0);
368
			$this->eventMapper->update($event);
369
			sort($chosenDates);
370 View Code Duplication
			foreach ($chosenDates as $el) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
371
				$date = new Date();
372
				$date->setPollId($pollId);
373
				$date->setDt(date('Y-m-d H:i:s', $el));
0 ignored issues
show
Bug introduced by
date('Y-m-d H:i:s', $el) of type string is incompatible with the type OCA\Polls\Db\timestamp expected by parameter $value of OCA\Polls\Db\Date::setDt(). ( Ignorable by Annotation )

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

373
				$date->setDt(/** @scrutinizer ignore-type */ date('Y-m-d H:i:s', $el));
Loading history...
374
				$this->dateMapper->insert($date);
375
			}
376
		} else {
377
			$event->setType(1);
378
			$this->eventMapper->update($event);
379
			foreach ($chosenDates as $el) {
380
				$text = new Text();
381
				$text->setText($el);
382
				$text->setPollId($pollId);
383
				$this->textMapper->insert($text);
384
			}
385
		}
386
		$url = $this->urlGenerator->linkToRoute('polls.page.index');
387
		return new RedirectResponse($url);
388
	}
389
390
	/**
391
	 * @NoAdminRequired
392
	 * @NoCSRFRequired
393
	 */
394
	public function createPoll() {
395
		return new TemplateResponse('polls', 'create.tmpl',
396
			['userId' => $this->userId, 'userMgr' => $this->manager, 'urlGenerator' => $this->urlGenerator]);
397
	}
398
399
	/**
400
	 * @NoAdminRequired
401
	 * @NoCSRFRequired
402
	 * @param $pollType
403
	 * @param $pollTitle
404
	 * @param $pollDesc
405
	 * @param $userId
406
	 * @param $chosenDates
407
	 * @param $expireTs
408
	 * @param $accessType
409
	 * @param $accessValues
410
	 * @param $isAnonymous
411
	 * @param $hideNames
412
	 * @return RedirectResponse
413
	 */
414
	public function insertPoll(
415
		$pollType,
416
		$pollTitle,
417
		$pollDesc,
418
		$userId,
419
		$chosenDates,
420
		$expireTs,
421
		$accessType,
422
		$accessValues,
423
		$isAnonymous,
424
		$hideNames
425
	) {
426
		$event = new Event();
427
		$event->setTitle(htmlspecialchars($pollTitle));
428
		$event->setDescription(htmlspecialchars($pollDesc));
429
		$event->setOwner($userId);
430
		$event->setCreated(date('Y-m-d H:i:s'));
0 ignored issues
show
Bug introduced by
date('Y-m-d H:i:s') of type string is incompatible with the type OCA\Polls\Db\timestamp expected by parameter $value of OCA\Polls\Db\Event::setCreated(). ( Ignorable by Annotation )

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

430
		$event->setCreated(/** @scrutinizer ignore-type */ date('Y-m-d H:i:s'));
Loading history...
431
		$event->setHash(\OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(16,
432
			ISecureRandom::CHAR_DIGITS .
433
			ISecureRandom::CHAR_LOWER .
434
			ISecureRandom::CHAR_UPPER));
435
		$event->setIsAnonymous($isAnonymous ? 1 : 0);
436
		$event->setFullAnonymous($isAnonymous && $hideNames ? 1 : 0);
437
438 View Code Duplication
		if ($accessType === 'select') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
439
			if (isset($accessValues)) {
440
				$accessValues = json_decode($accessValues);
441
				if ($accessValues !== null) {
442
					$groups = array();
443
					$users = array();
444
					if ($accessValues->groups !== null) {
445
						$groups = $accessValues->groups;
446
					}
447
					if ($accessValues->users !== null) {
448
						$users = $accessValues->users;
449
					}
450
					$accessType = '';
451
					foreach ($groups as $gid) {
452
						$accessType .= $gid . ';';
453
					}
454
					foreach ($users as $uid) {
455
						$accessType .= $uid . ';';
456
					}
457
				}
458
			}
459
		}
460
		$event->setAccess($accessType);
461
462
		$chosenDates = json_decode($chosenDates);
463
464
		$expire = null;
465 View Code Duplication
		if ($expireTs !== null && $expireTs !== '') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
466
			$expire = date('Y-m-d H:i:s', $expireTs + 60 * 60 * 24); //add one day, so it expires at the end of a day
467
		}
468
		$event->setExpire($expire);
0 ignored issues
show
Bug introduced by
It seems like $expire can also be of type string; however, parameter $value of OCA\Polls\Db\Event::setExpire() does only seem to accept OCA\Polls\Db\timestamp, maybe add an additional type check? ( Ignorable by Annotation )

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

468
		$event->setExpire(/** @scrutinizer ignore-type */ $expire);
Loading history...
469
470
		if ($pollType === 'event') {
471
			$event->setType(0);
472
			$ins = $this->eventMapper->insert($event);
473
			$poll_id = $ins->getId();
474
			sort($chosenDates);
475 View Code Duplication
			foreach ($chosenDates as $el) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
476
				$date = new Date();
477
				$date->setPollId($poll_id);
478
				$date->setDt(date('Y-m-d H:i:s', $el));
0 ignored issues
show
Bug introduced by
date('Y-m-d H:i:s', $el) of type string is incompatible with the type OCA\Polls\Db\timestamp expected by parameter $value of OCA\Polls\Db\Date::setDt(). ( Ignorable by Annotation )

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

478
				$date->setDt(/** @scrutinizer ignore-type */ date('Y-m-d H:i:s', $el));
Loading history...
479
				$this->dateMapper->insert($date);
480
			}
481
		} else {
482
			$event->setType(1);
483
			$ins = $this->eventMapper->insert($event);
484
			$poll_id = $ins->getId();
485
			$cnt = 1;
486
			foreach ($chosenDates as $el) {
487
				$text = new Text();
488
				$text->setText($el . '_' . $cnt);
489
				$text->setPollId($poll_id);
490
				$this->textMapper->insert($text);
491
				$cnt++;
492
			}
493
		}
494
		$url = $this->urlGenerator->linkToRoute('polls.page.index');
495
		return new RedirectResponse($url);
496
	}
497
498
	/**
499
	 * @NoAdminRequired
500
	 * @NoCSRFRequired
501
	 * @PublicPage
502
	 * @param $pollId
503
	 * @param $userId
504
	 * @param $types
505
	 * @param $dates
506
	 * @param $receiveNotifications
507
	 * @param $changed
508
	 * @return RedirectResponse
509
	 */
510
	public function insertVote($pollId, $userId, $types, $dates, $receiveNotifications, $changed) {
511
		if ($this->userId !== null) {
512
			if ($receiveNotifications === 'true') {
513
				try {
514
					//check if user already set notification for this poll
515
					$this->notificationMapper->findByUserAndPoll($pollId, $userId);
516
				} catch (DoesNotExistException $e) {
517
					//insert if not exist
518
					$not = new Notification();
519
					$not->setUserId($userId);
520
					$not->setPollId($pollId);
521
					$this->notificationMapper->insert($not);
522
				}
523
			} else {
524
				try {
525
					//delete if entry is in db
526
					$not = $this->notificationMapper->findByUserAndPoll($pollId, $userId);
527
					$this->notificationMapper->delete($not);
528
				} catch (DoesNotExistException $e) {
529
					//doesn't exist in db, nothing to do
530
				}
531
			}
532
		}
533
		$poll = $this->eventMapper->find($pollId);
534
		if ($changed === 'true') {
535
			$dates = json_decode($dates);
536
			$types = json_decode($types);
537
			$count_dates = count($dates);
538
			if ($poll->getType() == '0') {
539
				$this->participationMapper->deleteByPollAndUser($pollId, $userId);
540
			} else {
541
				$this->participationTextMapper->deleteByPollAndUser($pollId, $userId);
542
			}
543
			for ($i = 0; $i < $count_dates; $i++) {
544
				if ($poll->getType() == '0') {
545
					$part = new Participation();
546
					$part->setPollId($pollId);
547
					$part->setUserId($userId);
548
					$part->setDt(date('Y-m-d H:i:s', $dates[$i]));
0 ignored issues
show
Bug introduced by
date('Y-m-d H:i:s', $dates[$i]) of type string is incompatible with the type OCA\Polls\Db\timestamp expected by parameter $value of OCA\Polls\Db\Participation::setDt(). ( Ignorable by Annotation )

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

548
					$part->setDt(/** @scrutinizer ignore-type */ date('Y-m-d H:i:s', $dates[$i]));
Loading history...
549
					$part->setType($types[$i]);
550
					$this->participationMapper->insert($part);
551
				} else {
552
					$part = new ParticipationText();
553
					$part->setPollId($pollId);
554
					$part->setUserId($userId);
555
					$part->setText($dates[$i]);
556
					$part->setType($types[$i]);
557
					$this->participationTextMapper->insert($part);
558
				}
559
560
			}
561
			$this->sendNotifications($pollId, $userId);
562
		}
563
		$hash = $poll->getHash();
564
		$url = $this->urlGenerator->linkToRoute('polls.page.goto_poll', ['hash' => $hash]);
565
		return new RedirectResponse($url);
566
	}
567
568
	/**
569
	 * @NoAdminRequired
570
	 * @NoCSRFRequired
571
	 * @PublicPage
572
	 * @param $pollId
573
	 * @param $userId
574
	 * @param $commentBox
575
	 * @return JSONResponse
576
	 */
577
	public function insertComment($pollId, $userId, $commentBox) {
578
		$comment = new Comment();
579
		$comment->setPollId($pollId);
580
		$comment->setUserId($userId);
581
		$comment->setComment($commentBox);
582
		$comment->setDt(date('Y-m-d H:i:s'));
583
		$this->commentMapper->insert($comment);
584
		$this->sendNotifications($pollId, $userId);
585
		if ($this->manager->get($userId) !== null) {
586
			$newUserId = $this->manager->get($userId)->getDisplayName();
587
		} else {
588
			$newUserId = $userId;
589
		}
590
		return new JSONResponse(array(
591
			'comment' => $commentBox,
592
			'date' => date('Y-m-d H:i:s'),
593
			'userName' => $newUserId
594
		));
595
	}
596
597
	/**
598
	 * @NoAdminRequired
599
	 * @NoCSRFRequired
600
	 * @param $searchTerm
601
	 * @param $groups
602
	 * @param $users
603
	 * @return array
604
	 */
605
	 public function search($searchTerm, $groups, $users) {
606
		return array_merge($this->searchForGroups($searchTerm, $groups), $this->searchForUsers($searchTerm, $users));
607
	}
608
609
	/**
610
	 * @NoAdminRequired
611
	 * @NoCSRFRequired
612
	 * @param $searchTerm
613
	 * @param $groups
614
	 * @return array
615
	 */
616
	 public function searchForGroups($searchTerm, $groups) {
617
		$selectedGroups = json_decode($groups);
618
		$groups = $this->groupManager->search($searchTerm);
619
		$gids = array();
620
		$sgids = array();
621
		foreach ($selectedGroups as $sg) {
622
			$sgids[] = str_replace('group_', '', $sg);
623
		}
624
		foreach ($groups as $g) {
625
			$gids[] = $g->getGID();
626
		}
627
		$diffGids = array_diff($gids, $sgids);
628
		$gids = array();
629
		foreach ($diffGids as $g) {
630
			$gids[] = ['gid' => $g, 'isGroup' => true];
631
		}
632
		return $gids;
633
	}
634
635
	/**
636
	 * @NoAdminRequired
637
	 * @NoCSRFRequired
638
	 * @param $searchTerm
639
	 * @param $users
640
	 * @return array
641
	 */
642
	 public function searchForUsers($searchTerm, $users) {
643
		$selectedUsers = json_decode($users);
644
		Util::writeLog("polls", print_r($selectedUsers, true), Util::ERROR);
645
		$userNames = $this->userMgr->searchDisplayName($searchTerm);
646
		$users = array();
647
		$sUsers = array();
648
		foreach ($selectedUsers as $su) {
649
			$sUsers[] = str_replace('user_', '', $su);
650
		}
651
		foreach ($userNames as $u) {
652
			$alreadyAdded = false;
653
			foreach ($sUsers as &$su) {
654
				if ($su === $u->getUID()) {
655
					unset($su);
656
					$alreadyAdded = true;
657
					break;
658
				}
659
			}
660
			if (!$alreadyAdded) {
661
				$users[] = array('uid' => $u->getUID(), 'displayName' => $u->getDisplayName(), 'isGroup' => false);
662
			} else {
663
				continue;
664
			}
665
		}
666
		return $users;
667
	}
668
669
	/**
670
	 * @NoAdminRequired
671
	 * @NoCSRFRequired
672
	 * @param $username
673
	 * @return string
674
	 */
675
	 public function getDisplayName($username) {
676
		return $this->manager->get($username)->getDisplayName();
677
	}
678
679
	/**
680
	 * @return Event[]
681
	 */
682
	 public function getPollsForUser() {
683
		return $this->eventMapper->findAllForUser($this->userId);
684
	}
685
686
	/**
687
	 * @param $user
688
	 * @return Event[]
689
	 */
690
	 public function getPollsForUserWithInfo($user = null) {
691
		if ($user === null) {
692
			return $this->eventMapper->findAllForUserWithInfo($this->userId);
693
		} else {
694
			return $this->eventMapper->findAllForUserWithInfo($user);
695
		}
696
	}
697
	/**
698
	 * @return array
699
	 */
700 View Code Duplication
	 public function getGroups() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
701
		// $this->requireLogin();
702
		if (class_exists('\OC_Group', true)) {
703
			// Nextcloud <= 11, ownCloud
704
			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...
705
		}
706
		// Nextcloud >= 12
707
		$groups = \OC::$server->getGroupManager()->getUserGroups(\OC::$server->getUserSession()->getUser());
708
		return array_map(function ($group) {
709
			return $group->getGID();
710
		}, $groups);
711
	}
712
713
	/**
714
	 * @param $poll
715
	 * @return bool
716
	 */
717
	private function hasUserAccess($poll) {
718
		$access = $poll->getAccess();
719
		$owner = $poll->getOwner();
720
		if ($access === 'public') {
721
			return true;
722
		}
723
		if ($access === 'hidden') {
724
			return true;
725
		}
726
		if ($this->userId === null) {
727
			return false;
728
		}
729
		if ($access === 'registered') {
730
			return true;
731
		}
732
		if ($owner === $this->userId) {
733
			return true;
734
		}
735
		Util::writeLog("polls", $this->userId, Util::ERROR);
736
		$user_groups = $this->getGroups();
737
		$arr = explode(';', $access);
738
		foreach ($arr as $item) {
739
			if (strpos($item, 'group_') === 0) {
740
				$grp = substr($item, 6);
741
				foreach ($user_groups as $user_group) {
742
					if ($user_group === $grp) {
743
						return true;
744
					}
745
				}
746
			} else {
747
				if (strpos($item, 'user_') === 0) {
748
					$usr = substr($item, 5);
749
					if ($usr === User::getUser()) {
750
						return true;
751
					}
752
				}
753
			}
754
		}
755
		return false;
756
	}
757
}
758