Completed
Pull Request — master (#564)
by Thomas
03:30
created

MailQueueHandler   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 250
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 28.13%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 17
lcom 1
cbo 2
dl 0
loc 250
ccs 27
cts 96
cp 0.2813
rs 10
c 1
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 15 1
A getAffectedUsers() 0 23 3
B getItemsForUser() 0 32 3
A getLanguage() 0 7 2
A getSenderData() 0 14 4
A sendEmailToUser() 0 55 3
A deleteSentItems() 0 11 1
1
<?php
2
/**
3
 * @author Joas Schilling <[email protected]>
4
 *
5
 * @copyright Copyright (c) 2016, ownCloud, Inc.
6
 * @license AGPL-3.0
7
 *
8
 * This code is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU Affero General Public License, version 3,
10
 * as published by the Free Software Foundation.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License, version 3,
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
19
 *
20
 */
21
22
namespace OCA\Activity;
23
24
use OCP\Activity\IManager;
25
use OCP\Defaults;
26
use OCP\IDateTimeFormatter;
27
use OCP\IDBConnection;
28
use OCP\IURLGenerator;
29
use OCP\IUser;
30
use OCP\IUserManager;
31
use OCP\Mail\IMailer;
32
use OCP\Template;
33
use OCP\Util;
34
35
/**
36
 * Class MailQueueHandler
37
 * Gets the users from the database and
38
 *
39
 * @package OCA\Activity
40
 */
41
class MailQueueHandler {
42
	/** Number of entries we want to list in the email */
43
	const ENTRY_LIMIT = 200;
44
45
	/** @var array */
46
	protected $languages;
47
48
	/** @var string */
49
	protected $senderAddress;
50
51
	/** @var string */
52
	protected $senderName;
53
54
	/** @var IDateTimeFormatter */
55
	protected $dateFormatter;
56
57
	/** @var DataHelper */
58
	protected $dataHelper;
59
60
	/** @var IDBConnection */
61
	protected $connection;
62
63
	/** @var IMailer */
64
	protected $mailer;
65
66
	/** @var IURLGenerator */
67
	protected $urlGenerator;
68
69
	/** @var IUserManager */
70
	protected $userManager;
71
72
	/** @var IManager */
73
	protected $activityManager;
74
75
	/**
76
	 * Constructor
77
	 *
78
	 * @param IDateTimeFormatter $dateFormatter
79
	 * @param IDBConnection $connection
80
	 * @param DataHelper $dataHelper
81
	 * @param IMailer $mailer
82
	 * @param IURLGenerator $urlGenerator
83
	 * @param IUserManager $userManager
84
	 * @param IManager $activityManager
85
	 */
86 9
	public function __construct(IDateTimeFormatter $dateFormatter,
87
								IDBConnection $connection,
88
								DataHelper $dataHelper,
89
								IMailer $mailer,
90
								IURLGenerator $urlGenerator,
91
								IUserManager $userManager,
92
								IManager $activityManager) {
93 9
		$this->dateFormatter = $dateFormatter;
94 9
		$this->connection = $connection;
95 9
		$this->dataHelper = $dataHelper;
96 9
		$this->mailer = $mailer;
97 9
		$this->urlGenerator = $urlGenerator;
98 9
		$this->userManager = $userManager;
99 9
		$this->activityManager = $activityManager;
100 9
	}
101
102
	/**
103
	 * Get the users we want to send an email to
104
	 *
105
	 * @param int|null $limit
106
	 * @param int $latestSend
107
	 * @return array
108
	 */
109 7
	public function getAffectedUsers($limit, $latestSend) {
110 7
		$limit = (!$limit) ? null : (int) $limit;
111
112 7
		$query = $this->connection->prepare(
113
			'SELECT `amq_affecteduser`, `email`, MIN(`amq_latest_send`) AS `amq_trigger_time` '
114
			. ' FROM `*PREFIX*activity_mq` '
115
			. ' JOIN `*PREFIX*oc_accounts` ON `user_id` = `amq_affecteduser` '
116
			. ' WHERE `amq_latest_send` < ? '
117
			. ' GROUP BY `amq_affecteduser` '
118 7
			. ' ORDER BY `amq_trigger_time` ASC',
119
			$limit);
120
		$query->execute(array($latestSend));
121
122
		$affectedUsers = array();
123
		while ($row = $query->fetch()) {
124
			$affectedUsers[] = [
125
				'uid' => $row['amq_affecteduser'],
126
				'email' => $row['email']
127
			];
128
		}
129
130
		return $affectedUsers;
131
	}
132
133
	/**
134
	 * Get all items for the user we want to send an email to
135
	 *
136
	 * @param string $affectedUser
137
	 * @param int $maxTime
138
	 * @param int $maxNumItems
139
	 * @return array [data of the first max. 200 entries, total number of entries]
140
	 */
141 1
	protected function getItemsForUser($affectedUser, $maxTime, $maxNumItems = self::ENTRY_LIMIT) {
142 1
		$query = $this->connection->prepare(
143
			'SELECT * '
144
			. ' FROM `*PREFIX*activity_mq` '
145
			. ' WHERE `amq_timestamp` <= ? '
146
			. ' AND `amq_affecteduser` = ? '
147 1
			. ' ORDER BY `amq_timestamp` ASC',
148
			$maxNumItems
149
		);
150 1
		$query->execute([(int) $maxTime, $affectedUser]);
151
152 1
		$activities = array();
153 1
		while ($row = $query->fetch()) {
154 1
			$activities[] = $row;
155
		}
156
157 1
		if (isset($activities[$maxNumItems - 1])) {
158
			// Reached the limit, run a query to get the actual count.
159 1
			$query = $this->connection->prepare(
160
				'SELECT COUNT(*) AS `actual_count`'
161
				. ' FROM `*PREFIX*activity_mq` '
162
				. ' WHERE `amq_timestamp` <= ? '
163 1
				. ' AND `amq_affecteduser` = ?'
164
			);
165 1
			$query->execute([(int) $maxTime, $affectedUser]);
166
167 1
			$row = $query->fetch();
168 1
			return [$activities, $row['actual_count'] - $maxNumItems];
169
		} else {
170 1
			return [$activities, 0];
171
		}
172
	}
173
174
	/**
175
	 * Get a language object for a specific language
176
	 *
177
	 * @param string $lang Language identifier
178
	 * @return \OCP\IL10N Language object of $lang
179
	 */
180
	protected function getLanguage($lang) {
181
		if (!isset($this->languages[$lang])) {
182
			$this->languages[$lang] = Util::getL10N('activity', $lang);
183
		}
184
185
		return $this->languages[$lang];
186
	}
187
188
	/**
189
	 * Get the sender data
190
	 * @param string $setting Either `email` or `name`
191
	 * @return string
192
	 */
193
	protected function getSenderData($setting) {
194
		if (empty($this->senderAddress)) {
195
			$this->senderAddress = Util::getDefaultEmailAddress('no-reply');
196
		}
197
		if (empty($this->senderName)) {
198
			$defaults = new Defaults();
199
			$this->senderName = $defaults->getName();
200
		}
201
202
		if ($setting === 'email') {
203
			return $this->senderAddress;
204
		}
205
		return $this->senderName;
206
	}
207
208
	/**
209
	 * Send a notification to one user
210
	 *
211
	 * @param string $userName Username of the recipient
212
	 * @param string $email Email address of the recipient
213
	 * @param string $lang Selected language of the recipient
214
	 * @param string $timezone Selected timezone of the recipient
215
	 * @param int $maxTime
216
	 */
217
	public function sendEmailToUser($userName, $email, $lang, $timezone, $maxTime) {
218
		$user = $this->userManager->get($userName);
219
		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...
220
			return;
221
		}
222
223
		list($mailData, $skippedCount) = $this->getItemsForUser($userName, $maxTime);
224
225
		$l = $this->getLanguage($lang);
226
		$parser = new PlainTextParser($l);
227
		$this->dataHelper->setUser($userName);
228
		$this->dataHelper->setL10n($l);
229
		$this->activityManager->setCurrentUserId($userName);
230
231
		$activityList = array();
232
		foreach ($mailData as $activity) {
233
			$event = $this->activityManager->generateEvent();
234
			$event->setApp($activity['amq_appid'])
235
				->setType($activity['amq_type'])
236
				->setTimestamp($activity['amq_timestamp'])
237
				->setSubject($activity['amq_subject'], []);
238
239
			$relativeDateTime = $this->dateFormatter->formatDateTimeRelativeDay(
240
				$activity['amq_timestamp'],
241
				'long', 'medium',
242
				new \DateTimeZone($timezone), $l
243
			);
244
245
			$activityList[] = array(
246
				$parser->parseMessage(
247
					$this->dataHelper->translation(
248
						$activity['amq_appid'], $activity['amq_subject'], $this->dataHelper->getParameters($event, 'subject', $activity['amq_subjectparams'])
249
					)
250
				),
251
				$relativeDateTime,
252
			);
253
		}
254
255
		$alttext = new Template('activity', 'email.notification', '', false);
256
		$alttext->assign('username', $user->getDisplayName());
257
		$alttext->assign('activities', $activityList);
258
		$alttext->assign('skippedCount', $skippedCount);
259
		$alttext->assign('owncloud_installation', $this->urlGenerator->getAbsoluteURL('/'));
260
		$alttext->assign('overwriteL10N', $l);
261
		$emailText = $alttext->fetchPage();
262
263
		$message = $this->mailer->createMessage();
264
		$message->setTo([$email => $user->getDisplayName()]);
265
		$message->setSubject((string) $l->t('Activity notification'));
266
		$message->setPlainBody($emailText);
267
		$message->setFrom([$this->getSenderData('email') => $this->getSenderData('name')]);
268
		$this->mailer->send($message);
269
270
		$this->activityManager->setCurrentUserId(null);
271
	}
272
273
	/**
274
	 * Delete all entries we dealt with
275
	 *
276
	 * @param array $affectedUsers
277
	 * @param int $maxTime
278
	 */
279
	public function deleteSentItems($affectedUsers, $maxTime) {
280
		$placeholders = implode(',', array_fill(0, sizeof($affectedUsers), '?'));
281
		$queryParams = $affectedUsers;
282
		array_unshift($queryParams, (int) $maxTime);
283
284
		$query = $this->connection->prepare(
285
			'DELETE FROM `*PREFIX*activity_mq` '
286
			. ' WHERE `amq_timestamp` <= ? '
287
			. ' AND `amq_affecteduser` IN (' . $placeholders . ')');
288
		$query->execute($queryParams);
289
	}
290
}
291