Completed
Push — master ( 0da6ae...09fb36 )
by René
06:04 queued 01:33
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 2
Bugs 1 Features 0
Metric Value
cc 1
eloc 13
c 2
b 1
f 0
nc 1
nop 14
dl 0
loc 31
ccs 0
cts 29
cp 0
crap 2
rs 9.8333

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 ShareMapper $shareMapper
78
	 * @param EventMapper $eventMapper
79
	 * @param IConfig $config
80
	 * @param IURLGenerator $urlGenerator
81
	 * @param IUserManager $userMgr
82
	 * @param IGroupManager $groupMgr
83
	 * @param IL10N $trans
84
	 * @param IFactory $transFactory
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()))
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
		$contactsManager = \OC::$server->getContactsManager();
233
234
		if ($share->getType() === 'user') {
235
236
			$recipients[] = array(
237
				'userId' => $share->getUserId(),
238
				'displayName' => $this->userMgr->get($share->getUserId())->getDisplayName(),
239
				'language' => $this->config->getUserValue($share->getUserId(), 'core', 'lang'),
240
				'eMail' => $this->userMgr->get($share->getUserId())->getEMailAddress(),
241
				'link' => $this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkToRoute('polls.page.vote_poll', array('pollId' => $share->getpollId())))
242
			);
243
244
		} elseif ($share->getType() === 'contact') {
245
			$contacts = $contactsManager->search($share->getUserId(), array('UID'));
246
			if (is_array($contacts)) {
247
				$contact = $contact[0];
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $contact does not exist. Did you maybe mean $contactsManager?
Loading history...
248
249
				$recipients[] = array(
250
					'userId' => $share->getUserId(),
251
					'displayName' => $contact['FN'],
252
					'language' => $this->config->getUserValue($event->getOwner(), 'core', 'lang'),
253
					'eMail' => $contact['EMAIL'][0],
254
					'link' => $this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkToRoute('polls.page.vote_poll', array('pollId' => $share->getpollId())))
255
				);
256
			} else {
257
				return;
258
			}
259
260
		} elseif ($share->getType() === 'external' || $share->getType() === 'mail') {
261
262
			$recipients[] = array(
263
				'userId' => $share->getUserId(),
264
				'displayName' => $share->getUserId(),
265
				'language' => $this->config->getUserValue($event->getOwner(), 'core', 'lang'),
266
				'eMail' => $share->getUserEmail(),
267
				'link' => $this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkToRoute('polls.page.vote_public', array('token' => $share->getToken())))
268
			);
269
270
		} elseif ($share->getType() === 'group') {
271
272
			$groupMembers = array_keys($this->groupMgr->displayNamesInGroup($share->getUserId()));
273
274
			foreach ($groupMembers as $member) {
275
				if ($event->getOwner() === $member) {
276
					continue;
277
				}
278
279
				$recipients[] = array(
280
					'userId' => $member,
281
					'displayName' => $this->userMgr->get($member)->getDisplayName(),
282
					'language' => $this->config->getUserValue($share->getUserId(), 'core', 'lang'),
283
					'eMail' => $this->userMgr->get($member)->getEMailAddress(),
284
					'link' => $this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkToRoute('polls.page.vote_poll', array('pollId' => $share->getpollId())))
285
				);
286
287
			}
288
		}
289
290
		$sendUser = $this->userMgr->get($event->getOwner());
291
		$sender = $event->getOwner();
292
		if ($sendUser instanceof IUser) {
293
			$sender = $sendUser->getDisplayName();
294
		}
295
296
		foreach ($recipients as $recipient) {
297
298
			if ($recipient['eMail'] === null || !filter_var($recipient['eMail'], FILTER_VALIDATE_EMAIL)) {
299
				continue;
300
			}
301
302
			$trans = $this->transFactory->get('polls', $recipient['language']);
303
304
			$emailTemplate = $this->mailer->createEMailTemplate('polls.Invitation', [
305
				'user' => $sender,
306
				'title' => $event->getTitle(),
307
				'link' => $recipient['link']
308
			]);
309
310
			$emailTemplate->setSubject($trans->t('Poll invitation "%s"', $event->getTitle()));
311
			$emailTemplate->addHeader();
312
			$emailTemplate->addHeading($trans->t('Poll invitation "%s"', $event->getTitle()), false);
313
314
			$emailTemplate->addBodyText(str_replace(
315
				['{user}', '{title}'],
316
				[$sender, $event->getTitle()],
317
				$trans->t('{user} invited you to take part in the poll "{title}"' )
318
			));
319
320
				$emailTemplate->addBodyButton(
321
					htmlspecialchars($trans->t('Go to poll')),
322
					$recipient['link']
323
				);
324
325
			$emailTemplate->addFooter();
326
327
			try {
328
329
				$message = $this->mailer->createMessage();
330
				$message->setTo([$recipient['eMail'] => $recipient['displayName']]);
331
				$message->useTemplate($emailTemplate);
332
				$this->mailer->send($message);
333
334
			} catch (\Exception $e) {
335
336
				$this->logger->logException($e, ['app' => 'polls']);
337
338
			}
339
		}
340
	}
341
342
}
343