Completed
Push — master ( d31297...b14507 )
by René
04:36 queued 12s
created

NotificationController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 31
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 13
nc 1
nop 14
dl 0
loc 31
ccs 0
cts 29
cp 0
crap 2
rs 9.8333
c 1
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 René Gieling <[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 Exception;
27
use OCP\AppFramework\Db\DoesNotExistException;
28
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
29
30
use OCP\IRequest;
31
use OCP\ILogger;
32
use OCP\IConfig;
33
use OCP\IUser;
34
use OCP\IUserManager;
35
use OCP\IGroup;
36
use OCP\IGroupManager;
37
use OCP\IL10N;
38
use OCP\L10N\IFactory;
39
use OCP\IURLGenerator;
40
use OCP\Mail\IMailer;
41
42
use OCP\AppFramework\Controller;
43
use OCP\AppFramework\Http;
44
use OCP\AppFramework\Http\DataResponse;
45
46
use OCA\Polls\Db\Event;
47
use OCA\Polls\Db\EventMapper;
48
use OCA\Polls\Db\Share;
49
use OCA\Polls\Db\ShareMapper;
50
use OCA\Polls\Db\Notification;
51
use OCA\Polls\Db\NotificationMapper;
52
53
class NotificationController extends Controller {
54
55
	private $userId;
56
	private $mapper;
57
	private $logger;
58
59
	private $eventMapper;
60
	private $shareMapper;
61
62
	private $config;
63
	private $urlGenerator;
64
	private $userMgr;
65
	private $groupMgr;
66
	private $trans;
67
	private $transFactory;
68
	private $mailer;
69
70
	/**
71
	 * NotificationController constructor.
72
	 * @param string $appName
73
	 * @param $UserId
74
	 * @param NotificationMapper $mapper
75
	 * @param IRequest $request
76
	 * @param ILogger $logger
77
	 * @param EventMapper $eventMapper
78
	 * @param ShareMapper $shareMapper
79
	 * @param IConfig $config
80
	 * @param IUserManager $userMgr
81
	 * @param IGroupManager $groupMgr
82
	 * @param IL10N $trans
83
	 * @param IFactory $transFactory
84
	 * @param IURLGenerator $urlGenerator
85
	 * @param IMailer $mailer
86
	 */
87
88
	public function __construct(
89
		string $appName,
90
		$UserId,
91
		NotificationMapper $mapper,
92
		IRequest $request,
93
		ILogger $logger,
94
		ShareMapper $shareMapper,
95
		EventMapper $eventMapper,
96
		IConfig $config,
97
		IURLGenerator $urlGenerator,
98
		IUserManager $userMgr,
99
		IGroupManager $groupMgr,
100
		IL10N $trans,
101
		IFactory $transFactory,
102
		IMailer $mailer
103
104
	) {
105
		parent::__construct($appName, $request);
106
		$this->userId = $UserId;
107
		$this->mapper = $mapper;
108
		$this->logger = $logger;
109
		$this->eventMapper = $eventMapper;
110
		$this->shareMapper = $shareMapper;
111
112
		$this->config = $config;
113
		$this->userMgr = $userMgr;
114
		$this->groupMgr = $groupMgr;
115
		$this->trans = $trans;
116
		$this->transFactory = $transFactory;
117
		$this->urlGenerator = $urlGenerator;
118
		$this->mailer = $mailer;
119
120
	}
121
122
	/**
123
	 * @NoAdminRequired
124
	 * @param integer $pollId
125
	 * @return DataResponse
126
	 */
127
	public function get($pollId) {
128
129
		if (!\OC::$server->getUserSession()->isLoggedIn()) {
130
			return new DataResponse(null, Http::STATUS_UNAUTHORIZED);
131
		}
132
133
		try {
134
			$this->mapper->findByUserAndPoll($pollId, $this->userId);
135
		} catch (MultipleObjectsReturnedException $e) {
136
			// should not happen, but who knows
137
		} catch (DoesNotExistException $e) {
138
			return new DataResponse(null, Http::STATUS_NOT_FOUND);
139
		}
140
		return new DataResponse(null, Http::STATUS_OK);
141
	}
142
143
	/**
144
	 * @NoAdminRequired
145
	 * @param integer $pollId
146
	 */
147
	public function set($pollId, $subscribed) {
148
		if ($subscribed) {
149
			$notification = new Notification();
150
			$notification->setPollId($pollId);
151
			$notification->setUserId($this->userId);
152
			$this->mapper->insert($notification);
153
			return true;
154
		} else {
155
			$this->mapper->unsubscribe($pollId, $this->userId);
156
			return false;
157
		}
158
	}
159
160
	/**
161
	 * @param int $pollId
162
	 * @param string $from
163
	 */
164
	private function sendNotifications($pollId, $from) {
165
		$poll = $this->eventMapper->find($pollId);
166
		$notifications = $this->mapper->findAllByPoll($pollId);
167
		foreach ($notifications as $notification) {
168
			if ($from === $notification->getUserId()) {
169
				continue;
170
			}
171
			$recUser = $this->userMgr->get($notification->getUserId());
172
			if (!$recUser instanceof IUser) {
173
				continue;
174
			}
175
			$email = \OC::$server->getConfig()->getUserValue($notification->getUserId(), 'settings', 'email');
176
			if ($email === null || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
177
				continue;
178
			}
179
			$url = $this->urlGenerator->getAbsoluteURL(
180
				$this->urlGenerator->linkToRoute('polls.page.vote',
181
					array('hash' => $poll->getHash()))
0 ignored issues
show
Bug introduced by
The method getHash() does not exist on OCA\Polls\Db\Event. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

181
					array('hash' => $poll->/** @scrutinizer ignore-call */ getHash()))
Loading history...
182
			);
183
184
			$sendUser = $this->userMgr->get($from);
185
			$sender = $from;
186
			if ($sendUser instanceof IUser) {
187
				$sender = $sendUser->getDisplayName();
188
			}
189
190
			$lang = $this->config->getUserValue($notification->getUserId(), 'core', 'lang');
191
			$trans = $this->transFactory->get('polls', $lang);
192
			$emailTemplate = $this->mailer->createEMailTemplate('polls.Notification', [
193
				'user' => $sender,
194
				'title' => $poll->getTitle(),
195
				'link' => $url,
196
			]);
197
			$emailTemplate->setSubject($trans->t('Polls App - New Activity'));
198
			$emailTemplate->addHeader();
199
			$emailTemplate->addHeading($trans->t('Polls App - New Activity'), false);
200
201
			$emailTemplate->addBodyText(str_replace(
202
				['{user}', '{title}'],
203
				[$sender, $poll->getTitle()],
204
				$trans->t('{user} participated in the poll "{title}"')
205
			));
206
207
			$emailTemplate->addBodyButton(
208
				htmlspecialchars($trans->t('Go to poll')),
209
				$url,
210
				/** @scrutinizer ignore-type */ false
211
			);
212
213
			$emailTemplate->addFooter();
214
			try {
215
				$message = $this->mailer->createMessage();
216
				$message->setTo([$email => $recUser->getDisplayName()]);
217
				$message->useTemplate($emailTemplate);
218
				$this->mailer->send($message);
219
			} catch (\Exception $e) {
220
				$this->logger->logException($e, ['app' => 'polls']);
221
			}
222
		}
223
	}
224
225
	/**
226
	 * @param string $token
227
	 */
228
	public function sendInvitationMail($token) {
229
		$recipients = [];
230
		$share = $this->shareMapper->findByToken($token);
231
		$event = $this->eventMapper->find($share->getPollId());
232
233
		if ($share->getType() === 'user') {
234
			$recipients[] = array(
235
				'userId' => $share->getUserId(),
236
				'displayName' => $this->userMgr->get($share->getUserId())->getDisplayName(),
237
				'language' => $this->config->getUserValue($share->getUserId(), 'core', 'lang'),
238
				'eMail' => $this->userMgr->get($share->getUserId())->getEMailAddress(),
239
				'link' => $this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkToRoute('polls.page.vote_poll', array('pollId' => $share->getpollId())))
240
			);
241
242
		} elseif ($share->getType() === 'external' || $share->getType() === 'mail') {
243
			$recipients[] = array(
244
				'userId' => $share->getUserId(),
245
				'displayName' => $share->getUserId(),
246
				'language' => $this->config->getUserValue($share->getOwner(), 'core', 'lang'),
247
				'eMail' => $this->userMgr->get($share->getUserId())->getEmail(),
0 ignored issues
show
Bug introduced by
The method getEmail() does not exist on OCP\IUser. ( Ignorable by Annotation )

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

247
				'eMail' => $this->userMgr->get($share->getUserId())->/** @scrutinizer ignore-call */ getEmail(),

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
248
				'link' => $this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkToRoute('polls.page.vote_public', array('token' => $share->getToken())))
249
			);
250
		} elseif ($share->getType() === 'group') {
251
			$groupMembers = array_keys($this->groupMgr->displayNamesInGroup($share->getUserId()));
252
			foreach ($groupMembers as $member) {
253
				if ($event->getOwner() === $member) {
254
					continue;
255
				}
256
				$recipients[] = array(
257
					'userId' => $member,
258
					'displayName' => $this->userMgr->get($member)->getDisplayName(),
259
					'language' => $this->config->getUserValue($share->getUserId(), 'core', 'lang'),
260
					'eMail' => $this->userMgr->get($member)->getEMailAddress(),
261
					'link' => $this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkToRoute('polls.page.vote_poll', array('pollId' => $share->getpollId())))
262
				);
263
			}
264
		}
265
266
		$sendUser = $this->userMgr->get($event->getOwner());
267
		$sender = $event->getOwner();
268
		if ($sendUser instanceof IUser) {
269
			$sender = $sendUser->getDisplayName();
270
		}
271
272
		foreach ($recipients as $recipient) {
273
274
			if ($recipient['eMail'] === null || !filter_var($recipient['eMail'], FILTER_VALIDATE_EMAIL)) {
275
				continue;
276
			}
277
278
			$trans = $this->transFactory->get('polls', $recipient['language']);
279
280
			$emailTemplate = $this->mailer->createEMailTemplate('polls.Invitation', [
281
				'user' => $sender,
282
				'title' => $event->getTitle(),
283
				'link' => $recipient['link']
284
			]);
285
			$emailTemplate->setSubject($trans->t('Poll invitation', 1, $event->getTitle()));
0 ignored issues
show
Unused Code introduced by
The call to OCP\IL10N::t() has too many arguments starting with $event->getTitle(). ( Ignorable by Annotation )

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

285
			$emailTemplate->setSubject($trans->/** @scrutinizer ignore-call */ t('Poll invitation', 1, $event->getTitle()));

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
286
			$emailTemplate->addHeader();
287
			$emailTemplate->addHeading($trans->t('Poll invitation', 1, $event->getTitle()), false);
288
289
			$emailTemplate->addBodyText(str_replace(
290
				['{user}', '{title}'],
291
				[$sender, $event->getTitle()],
292
				$trans->t('{user} invited you to take part in the poll "{title}"' )
293
			));
294
295
				$emailTemplate->addBodyButton(
296
					htmlspecialchars($trans->t('Go to poll')),
297
					$recipient['link'],
298
					/** @scrutinizer ignore-type */ false
299
				);
300
301
			$emailTemplate->addFooter();
302
303
			try {
304
				$message = $this->mailer->createMessage();
305
				$message->setTo([$recipient['eMail'] => $recipient['displayName']]);
306
				$message->useTemplate($emailTemplate);
307
				$this->mailer->send($message);
308
			} catch (\Exception $e) {
309
				$this->logger->logException($e, ['app' => 'polls']);
310
			}
311
		}
312
	}
313
314
}
315