Passed
Push — dartcafe-patch-1 ( 095f44...8dca15 )
by René
02:32
created

PageController::getGroups()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 11
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 11
loc 11
c 1
b 0
f 0
rs 9.4285
cc 2
eloc 6
nc 2
nop 0
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
     * @return RedirectResponse
310
     */
311
    public function updatePoll(
312
        $pollId,
313
        $pollType,
314
        $pollTitle,
315
        $pollDesc,
316
        $userId,
317
        $chosenDates,
318
        $expireTs,
319
        $accessType,
320
        $accessValues
321
    ) {
322
        $event = $this->eventMapper->find($pollId);
323
        $event->setTitle(htmlspecialchars($pollTitle));
324
        $event->setDescription(htmlspecialchars($pollDesc));
325
326 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...
327
            if (isset($accessValues)) {
328
                $accessValues = json_decode($accessValues);
329
                if ($accessValues !== null) {
330
                    $groups = array();
331
                    $users = array();
332
                    if ($accessValues->groups !== null) {
333
                        $groups = $accessValues->groups;
334
                    }
335
                    if ($accessValues->users !== null) {
336
                        $users = $accessValues->users;
337
                    }
338
                    $accessType = '';
339
                    foreach ($groups as $gid) {
340
                        $accessType .= $gid . ';';
341
                    }
342
                    foreach ($users as $uid) {
343
                        $accessType .= $uid . ';';
344
                    }
345
                }
346
            }
347
        }
348
        $event->setAccess($accessType);
349
350
        $chosenDates = json_decode($chosenDates);
351
352
        $expire = null;
353 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...
354
            $expire = date('Y-m-d H:i:s', $expireTs + 60 * 60 * 24); //add one day, so it expires at the end of a day
355
        }
356
        $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

356
        $event->setExpire(/** @scrutinizer ignore-type */ $expire);
Loading history...
357
358
        $this->dateMapper->deleteByPoll($pollId);
359
        $this->textMapper->deleteByPoll($pollId);
360
        if ($pollType === 'event') {
361
            $event->setType(0);
362
            $this->eventMapper->update($event);
363
            sort($chosenDates);
364 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...
365
                $date = new Date();
366
                $date->setPollId($pollId);
367
                $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

367
                $date->setDt(/** @scrutinizer ignore-type */ date('Y-m-d H:i:s', $el));
Loading history...
368
                $this->dateMapper->insert($date);
369
            }
370
        } else {
371
            $event->setType(1);
372
            $this->eventMapper->update($event);
373
            foreach ($chosenDates as $el) {
374
                $text = new Text();
375
                $text->setText($el);
376
                $text->setPollId($pollId);
377
                $this->textMapper->insert($text);
378
            }
379
        }
380
        $url = $this->urlGenerator->linkToRoute('polls.page.index');
381
        return new RedirectResponse($url);
382
    }
383
384
    /**
385
     * @NoAdminRequired
386
     * @NoCSRFRequired
387
     */
388
    public function createPoll() {
389
        return new TemplateResponse('polls', 'create.tmpl',
390
            ['userId' => $this->userId, 'userMgr' => $this->manager, 'urlGenerator' => $this->urlGenerator]);
391
    }
392
393
    /**
394
     * @NoAdminRequired
395
     * @NoCSRFRequired
396
     * @param $pollType
397
     * @param $pollTitle
398
     * @param $pollDesc
399
     * @param $userId
400
     * @param $chosenDates
401
     * @param $expireTs
402
     * @param $accessType
403
     * @param $accessValues
404
     * @param $isAnonymous
405
     * @param $hideNames
406
     * @return RedirectResponse
407
     */
408
    public function insertPoll(
409
        $pollType,
410
        $pollTitle,
411
        $pollDesc,
412
        $userId,
413
        $chosenDates,
414
        $expireTs,
415
        $accessType,
416
        $accessValues,
417
        $isAnonymous,
418
        $hideNames
419
    ) {
420
        $event = new Event();
421
        $event->setTitle(htmlspecialchars($pollTitle));
422
        $event->setDescription(htmlspecialchars($pollDesc));
423
        $event->setOwner($userId);
424
        $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

424
        $event->setCreated(/** @scrutinizer ignore-type */ date('Y-m-d H:i:s'));
Loading history...
425
        $event->setHash(\OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(16,
426
            ISecureRandom::CHAR_DIGITS .
427
            ISecureRandom::CHAR_LOWER .
428
            ISecureRandom::CHAR_UPPER));
429
        $event->setIsAnonymous($isAnonymous ? 1 : 0);
430
        $event->setFullAnonymous($isAnonymous && $hideNames ? 1 : 0);
431
432 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...
433
            if (isset($accessValues)) {
434
                $accessValues = json_decode($accessValues);
435
                if ($accessValues !== null) {
436
                    $groups = array();
437
                    $users = array();
438
                    if ($accessValues->groups !== null) {
439
                        $groups = $accessValues->groups;
440
                    }
441
                    if ($accessValues->users !== null) {
442
                        $users = $accessValues->users;
443
                    }
444
                    $accessType = '';
445
                    foreach ($groups as $gid) {
446
                        $accessType .= $gid . ';';
447
                    }
448
                    foreach ($users as $uid) {
449
                        $accessType .= $uid . ';';
450
                    }
451
                }
452
            }
453
        }
454
        $event->setAccess($accessType);
455
456
        $chosenDates = json_decode($chosenDates);
457
458
        $expire = null;
459 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...
460
            $expire = date('Y-m-d H:i:s', $expireTs + 60 * 60 * 24); //add one day, so it expires at the end of a day
461
        }
462
        $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

462
        $event->setExpire(/** @scrutinizer ignore-type */ $expire);
Loading history...
463
464
        if ($pollType === 'event') {
465
            $event->setType(0);
466
            $ins = $this->eventMapper->insert($event);
467
            $poll_id = $ins->getId();
468
            sort($chosenDates);
469 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...
470
                $date = new Date();
471
                $date->setPollId($poll_id);
472
                $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

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

542
                    $part->setDt(/** @scrutinizer ignore-type */ date('Y-m-d H:i:s', $dates[$i]));
Loading history...
543
                    $part->setType($types[$i]);
544
                    $this->participationMapper->insert($part);
545
                } else {
546
                    $part = new ParticipationText();
547
                    $part->setPollId($pollId);
548
                    $part->setUserId($userId);
549
                    $part->setText($dates[$i]);
550
                    $part->setType($types[$i]);
551
                    $this->participationTextMapper->insert($part);
552
                }
553
554
            }
555
            $this->sendNotifications($pollId, $userId);
556
        }
557
        $hash = $poll->getHash();
558
        $url = $this->urlGenerator->linkToRoute('polls.page.goto_poll', ['hash' => $hash]);
559
        return new RedirectResponse($url);
560
    }
561
562
    /**
563
     * @NoAdminRequired
564
     * @NoCSRFRequired
565
     * @PublicPage
566
     * @param $pollId
567
     * @param $userId
568
     * @param $commentBox
569
     * @return JSONResponse
570
     */
571
    public function insertComment($pollId, $userId, $commentBox) {
572
        $comment = new Comment();
573
        $comment->setPollId($pollId);
574
        $comment->setUserId($userId);
575
        $comment->setComment($commentBox);
576
        $comment->setDt(date('Y-m-d H:i:s'));
577
        $this->commentMapper->insert($comment);
578
        $this->sendNotifications($pollId, $userId);
579
        if ($this->manager->get($userId) !== null) {
580
            $newUserId = $this->manager->get($userId)->getDisplayName();
581
        } else {
582
            $newUserId = $userId;
583
        }
584
        return new JSONResponse(array(
585
            'comment' => $commentBox,
586
            'date' => date('Y-m-d H:i:s'),
587
            'userName' => $newUserId
588
        ));
589
    }
590
591
    /**
592
     * @NoAdminRequired
593
     * @NoCSRFRequired
594
     * @param $searchTerm
595
     * @param $groups
596
     * @param $users
597
     * @return array
598
     */
599
/*     public function search($searchTerm, $groups, $users) {
600
        return array_merge($this->searchForGroups($searchTerm, $groups), $this->searchForUsers($searchTerm, $users));
601
    }
602
 */
603
    /**
604
     * @NoAdminRequired
605
     * @NoCSRFRequired
606
     * @param $searchTerm
607
     * @param $groups
608
     * @return array
609
     */
610
/*     public function searchForGroups($searchTerm, $groups) {
611
        $selectedGroups = json_decode($groups);
612
        $groups = $this->groupManager->search($searchTerm);
613
        $gids = array();
614
        $sgids = array();
615
        foreach ($selectedGroups as $sg) {
616
            $sgids[] = str_replace('group_', '', $sg);
617
        }
618
        foreach ($groups as $g) {
619
            $gids[] = $g->getGID();
620
        }
621
        $diffGids = array_diff($gids, $sgids);
622
        $gids = array();
623
        foreach ($diffGids as $g) {
624
            $gids[] = ['gid' => $g, 'isGroup' => true];
625
        }
626
        return $gids;
627
    }
628
 */
629
    /**
630
     * @NoAdminRequired
631
     * @NoCSRFRequired
632
     * @param $searchTerm
633
     * @param $users
634
     * @return array
635
     */
636
/*     public function searchForUsers($searchTerm, $users) {
637
        $selectedUsers = json_decode($users);
638
        Util::writeLog("polls", print_r($selectedUsers, true), Util::ERROR);
639
        $userNames = $this->userMgr->searchDisplayName($searchTerm);
640
        $users = array();
641
        $sUsers = array();
642
        foreach ($selectedUsers as $su) {
643
            $sUsers[] = str_replace('user_', '', $su);
644
        }
645
        foreach ($userNames as $u) {
646
            $alreadyAdded = false;
647
            foreach ($sUsers as &$su) {
648
                if ($su === $u->getUID()) {
649
                    unset($su);
650
                    $alreadyAdded = true;
651
                    break;
652
                }
653
            }
654
            if (!$alreadyAdded) {
655
                $users[] = array('uid' => $u->getUID(), 'displayName' => $u->getDisplayName(), 'isGroup' => false);
656
            } else {
657
                continue;
658
            }
659
        }
660
        return $users;
661
    }
662
 */
663
    /**
664
     * @NoAdminRequired
665
     * @NoCSRFRequired
666
     * @param $username
667
     * @return string
668
     */
669
/*     public function getDisplayName($username) {
670
        return $this->manager->get($username)->getDisplayName();
671
    }
672
 */
673
    /**
674
     * @return Event[]
675
     */
676
/*     public function getPollsForUser() {
677
        return $this->eventMapper->findAllForUser($this->userId);
678
    }
679
 */
680
    /**
681
     * @param $user
682
     * @return Event[]
683
     */
684
/*     public function getPollsForUserWithInfo($user = null) {
685
        if ($user === null) {
686
            return $this->eventMapper->findAllForUserWithInfo($this->userId);
687
        } else {
688
            return $this->eventMapper->findAllForUserWithInfo($user);
689
        }
690
    }
691
 */
692
    /**
693
     * @return array
694
     */
695
/*     public function getGroups() {
696
        // $this->requireLogin();
697
        if (class_exists('\OC_Group', true)) {
698
            // Nextcloud <= 11, ownCloud
699
            return \OC_Group::getUserGroups($this->userId);
700
        }
701
        // Nextcloud >= 12
702
        $groups = \OC::$server->getGroupManager()->getUserGroups(\OC::$server->getUserSession()->getUser());
703
        return array_map(function ($group) {
704
            return $group->getGID();
705
        }, $groups);
706
    }
707
 */
708
    /**
709
     * @param $poll
710
     * @return bool
711
     */
712
    private function hasUserAccess($poll) {
713
        $access = $poll->getAccess();
714
        $owner = $poll->getOwner();
715
        if ($access === 'public') {
716
            return true;
717
        }
718
        if ($access === 'hidden') {
719
            return true;
720
        }
721
        if ($this->userId === null) {
722
            return false;
723
        }
724
        if ($access === 'registered') {
725
            return true;
726
        }
727
        if ($owner === $this->userId) {
728
            return true;
729
        }
730
        Util::writeLog("polls", $this->userId, Util::ERROR);
731
        $user_groups = $this->getGroups();
732
        $arr = explode(';', $access);
733
        foreach ($arr as $item) {
734
            if (strpos($item, 'group_') === 0) {
735
                $grp = substr($item, 6);
736
                foreach ($user_groups as $user_group) {
737
                    if ($user_group === $grp) {
738
                        return true;
739
                    }
740
                }
741
            } else {
742
                if (strpos($item, 'user_') === 0) {
743
                    $usr = substr($item, 5);
744
                    if ($usr === User::getUser()) {
745
                        return true;
746
                    }
747
                }
748
            }
749
        }
750
        return false;
751
    }
752
}
753