Completed
Pull Request — master (#88)
by Joas
04:03
created

MailQueueHandler::sendEmailToUser()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 62
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 43
CRAP Score 5.0021

Importance

Changes 0
Metric Value
dl 0
loc 62
ccs 43
cts 45
cp 0.9556
rs 8.6652
c 0
b 0
f 0
cc 5
eloc 45
nc 7
nop 5
crap 5.0021

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Joas Schilling <[email protected]>
6
 * @author Lukas Reschke <[email protected]>
7
 *
8
 * @license AGPL-3.0
9
 *
10
 * This code is free software: you can redistribute it and/or modify
11
 * it under the terms of the GNU Affero General Public License, version 3,
12
 * as published by the Free Software Foundation.
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, version 3,
20
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
21
 *
22
 */
23
24
namespace OCA\Activity;
25
26
use OCA\Activity\Extension\LegacyParser;
27
use OCP\Activity\IEvent;
28
use OCP\Activity\IManager;
29
use OCP\Defaults;
30
use OCP\IDateTimeFormatter;
31
use OCP\IDBConnection;
32
use OCP\IURLGenerator;
33
use OCP\IUser;
34
use OCP\IUserManager;
35
use OCP\L10N\IFactory;
36
use OCP\Mail\IMailer;
37
use OCP\Template;
38
use OCP\Util;
39
40
/**
41
 * Class MailQueueHandler
42
 * Gets the users from the database and
43
 *
44
 * @package OCA\Activity
45
 */
46
class MailQueueHandler {
47
	/** Number of entries we want to list in the email */
48
	const ENTRY_LIMIT = 200;
49
50
	/** @var array */
51
	protected $languages;
52
53
	/** @var string */
54
	protected $senderAddress;
55
56
	/** @var string */
57
	protected $senderName;
58
59
	/** @var IDateTimeFormatter */
60
	protected $dateFormatter;
61
62
	/** @var DataHelper */
63
	protected $dataHelper;
64
65
	/** @var IDBConnection */
66
	protected $connection;
67
68
	/** @var IMailer */
69
	protected $mailer;
70
71
	/** @var IURLGenerator */
72
	protected $urlGenerator;
73
74
	/** @var IUserManager */
75
	protected $userManager;
76
77
	/** @var IFactory */
78
	protected $lFactory;
79
80
	/** @var IManager */
81
	protected $activityManager;
82
83
	/** @var LegacyParser */
84
	protected $legacyParser;
85
86
	/**
87
	 * Constructor
88
	 *
89
	 * @param IDateTimeFormatter $dateFormatter
90
	 * @param IDBConnection $connection
91
	 * @param DataHelper $dataHelper
92
	 * @param IMailer $mailer
93
	 * @param IURLGenerator $urlGenerator
94
	 * @param IUserManager $userManager
95
	 * @param IFactory $lFactory
96
	 * @param IManager $activityManager
97
	 * @param LegacyParser $legacyParser
98
	 */
99 10
	public function __construct(IDateTimeFormatter $dateFormatter,
100
								IDBConnection $connection,
101
								DataHelper $dataHelper,
102
								IMailer $mailer,
103
								IURLGenerator $urlGenerator,
104
								IUserManager $userManager,
105
								IFactory $lFactory,
106
								IManager $activityManager,
107
								LegacyParser $legacyParser) {
108 10
		$this->dateFormatter = $dateFormatter;
109 10
		$this->connection = $connection;
110 10
		$this->dataHelper = $dataHelper;
111 10
		$this->mailer = $mailer;
112 10
		$this->urlGenerator = $urlGenerator;
113 10
		$this->userManager = $userManager;
114 10
		$this->lFactory = $lFactory;
115 10
		$this->activityManager = $activityManager;
116 10
		$this->legacyParser = $legacyParser;
117 10
	}
118
119
	/**
120
	 * Get the users we want to send an email to
121
	 *
122
	 * @param int|null $limit
123
	 * @param int $latestSend
124
	 * @return array
125
	 */
126 6
	public function getAffectedUsers($limit, $latestSend) {
127 6
		$limit = (!$limit) ? null : (int) $limit;
128
129 6
		$query = $this->connection->prepare(
130
			'SELECT `amq_affecteduser`, MIN(`amq_latest_send`) AS `amq_trigger_time` '
131
			. ' FROM `*PREFIX*activity_mq` '
132 6
			. ' WHERE `amq_latest_send` < ? '
133 6
			. ' GROUP BY `amq_affecteduser` '
134 6
			. ' ORDER BY `amq_trigger_time` ASC',
135 6
			$limit);
136 6
		$query->execute(array($latestSend));
137
138 6
		$affectedUsers = array();
139 6
		while ($row = $query->fetch()) {
140 6
			$affectedUsers[] = $row['amq_affecteduser'];
141 6
		}
142
143 6
		return $affectedUsers;
144
	}
145
146
	/**
147
	 * Get all items for the user we want to send an email to
148
	 *
149
	 * @param string $affectedUser
150
	 * @param int $maxTime
151
	 * @param int $maxNumItems
152
	 * @return array [data of the first max. 200 entries, total number of entries]
153
	 */
154 7
	protected function getItemsForUser($affectedUser, $maxTime, $maxNumItems = self::ENTRY_LIMIT) {
155 7
		$query = $this->connection->prepare(
156
			'SELECT * '
157
			. ' FROM `*PREFIX*activity_mq` '
158 7
			. ' WHERE `amq_timestamp` <= ? '
159 7
			. ' AND `amq_affecteduser` = ? '
160 7
			. ' ORDER BY `amq_timestamp` ASC',
161
			$maxNumItems
162 7
		);
163 7
		$query->execute([(int) $maxTime, $affectedUser]);
164
165 7
		$activities = array();
166 7
		while ($row = $query->fetch()) {
167 7
			$activities[] = $row;
168 7
		}
169
170 7
		if (isset($activities[$maxNumItems - 1])) {
171
			// Reached the limit, run a query to get the actual count.
172 1
			$query = $this->connection->prepare(
173
				'SELECT COUNT(*) AS `actual_count`'
174
				. ' FROM `*PREFIX*activity_mq` '
175 1
				. ' WHERE `amq_timestamp` <= ? '
176 1
				. ' AND `amq_affecteduser` = ?'
177 1
			);
178 1
			$query->execute([(int) $maxTime, $affectedUser]);
179
180 1
			$row = $query->fetch();
181 1
			return [$activities, $row['actual_count'] - $maxNumItems];
182
		} else {
183 7
			return [$activities, 0];
184
		}
185
	}
186
187
	/**
188
	 * Get a language object for a specific language
189
	 *
190
	 * @param string $lang Language identifier
191
	 * @return \OCP\IL10N Language object of $lang
192
	 */
193 1
	protected function getLanguage($lang) {
194 1
		if (!isset($this->languages[$lang])) {
195 1
			$this->languages[$lang] = $this->lFactory->get('activity', $lang);
196 1
		}
197
198 1
		return $this->languages[$lang];
199
	}
200
201
	/**
202
	 * Get the sender data
203
	 * @param string $setting Either `email` or `name`
204
	 * @return string
205
	 */
206 1
	protected function getSenderData($setting) {
207 1
		if (empty($this->senderAddress)) {
208 1
			$this->senderAddress = Util::getDefaultEmailAddress('no-reply');
209 1
		}
210 1
		if (empty($this->senderName)) {
211 1
			$defaults = new Defaults();
212 1
			$this->senderName = $defaults->getName();
213 1
		}
214
215 1
		if ($setting === 'email') {
216 1
			return $this->senderAddress;
217
		}
218 1
		return $this->senderName;
219
	}
220
221
	/**
222
	 * Send a notification to one user
223
	 *
224
	 * @param string $userName Username of the recipient
225
	 * @param string $email Email address of the recipient
226
	 * @param string $lang Selected language of the recipient
227
	 * @param string $timezone Selected timezone of the recipient
228
	 * @param int $maxTime
229
	 * @return bool True if the entries should be removed, false otherwise
230
	 */
231 1
	public function sendEmailToUser($userName, $email, $lang, $timezone, $maxTime) {
232 1
		$user = $this->userManager->get($userName);
233 1
		if (!$user instanceof IUser) {
0 ignored issues
show
Bug introduced by
The class OCP\IUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
234 1
			return true;
235
		}
236
237 1
		list($mailData, $skippedCount) = $this->getItemsForUser($userName, $maxTime);
238
239 1
		$l = $this->getLanguage($lang);
240 1
		$this->dataHelper->setUser($userName);
241 1
		$this->dataHelper->setL10n($l);
242 1
		$this->activityManager->setCurrentUserId($userName);
243
244 1
		$activityList = array();
245 1
		foreach ($mailData as $activity) {
246 1
			$event = $this->activityManager->generateEvent();
247 1
			$event->setApp($activity['amq_appid'])
248 1
				->setType($activity['amq_type'])
249 1
				->setTimestamp((int) $activity['amq_timestamp'])
250 1
				->setSubject($activity['amq_subject'], json_decode($activity['amq_subjectparams'], true));
251
252 1
			$relativeDateTime = $this->dateFormatter->formatDateTimeRelativeDay(
253 1
				$activity['amq_timestamp'],
254 1
				'long', 'medium',
255 1
				new \DateTimeZone($timezone), $l
256 1
			);
257
258
			try {
259 1
				$event = $this->parseEvent($lang, $event);
260 1
			} catch (\InvalidArgumentException $e) {
261
				continue;
262
			}
263
264 1
			$activityList[] = array(
265 1
				$event->getParsedSubject(),
266 1
				$relativeDateTime,
267
			);
268 1
		}
269
270 1
		$alttext = new Template('activity', 'email.notification', '', false);
271 1
		$alttext->assign('username', $user->getDisplayName());
272 1
		$alttext->assign('activities', $activityList);
273 1
		$alttext->assign('skippedCount', $skippedCount);
274 1
		$alttext->assign('installation', $this->urlGenerator->getAbsoluteURL('/'));
275 1
		$alttext->assign('overwriteL10N', $l);
276 1
		$emailText = $alttext->fetchPage();
277
278 1
		$message = $this->mailer->createMessage();
279 1
		$message->setTo([$email => $user->getDisplayName()]);
280 1
		$message->setSubject((string) $l->t('Activity notification'));
281 1
		$message->setPlainBody($emailText);
282 1
		$message->setFrom([$this->getSenderData('email') => $this->getSenderData('name')]);
283
284
		try {
285 1
			$this->mailer->send($message);
286 1
		} catch (\Exception $e) {
287
			return false;
288
		}
289
290 1
		$this->activityManager->setCurrentUserId(null);
291 1
		return true;
292
	}
293
294
	/**
295
	 * @param string $lang
296
	 * @param IEvent $event
297
	 * @return IEvent
298
	 * @throws \InvalidArgumentException when the event could not be parsed
299
	 */
300 1
	protected function parseEvent($lang, IEvent $event) {
301 1
		foreach ($this->activityManager->getProviders() as $provider) {
302
			try {
303
				$this->activityManager->setFormattingObject($event->getObjectType(), $event->getObjectId());
304
				$event = $provider->parse($lang, $event);
305
				$this->activityManager->setFormattingObject('', 0);
306
			} catch (\InvalidArgumentException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
307
			}
308 1
		}
309
310 1
		if (!$event->getParsedSubject()) {
311 1
			$this->activityManager->setFormattingObject($event->getObjectType(), $event->getObjectId());
312 1
			$event = $this->legacyParser->parse($lang, $event);
313 1
			$this->activityManager->setFormattingObject('', 0);
314 1
		}
315
316 1
		return $event;
317
	}
318
319
	/**
320
	 * Delete all entries we dealt with
321
	 *
322
	 * @param array $affectedUsers
323
	 * @param int $maxTime
324
	 */
325 5
	public function deleteSentItems($affectedUsers, $maxTime) {
326 5
		$placeholders = implode(',', array_fill(0, sizeof($affectedUsers), '?'));
327 5
		$queryParams = $affectedUsers;
328 5
		array_unshift($queryParams, (int) $maxTime);
329
330 5
		$query = $this->connection->prepare(
331
			'DELETE FROM `*PREFIX*activity_mq` '
332
			. ' WHERE `amq_timestamp` <= ? '
333 5
			. ' AND `amq_affecteduser` IN (' . $placeholders . ')');
334 5
		$query->execute($queryParams);
335 5
	}
336
}
337