Completed
Pull Request — stable9.1 (#570)
by
unknown
05:22
created

MailQueueHandler::validateMailAddress()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
c 1
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 2
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 View Code Duplication
	public function __construct(IDateTimeFormatter $dateFormatter,
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
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`, MIN(`amq_latest_send`) AS `amq_trigger_time` '
114
			. ' FROM `*PREFIX*activity_mq` '
115 7
			. ' WHERE `amq_latest_send` < ? '
116 7
			. ' GROUP BY `amq_affecteduser` '
117 7
			. ' ORDER BY `amq_trigger_time` ASC',
118 7
			$limit);
119 7
		$query->execute(array($latestSend));
120
121 7
		$affectedUsers = array();
122 7
		while ($row = $query->fetch()) {
123 6
			$affectedUsers[] = $row['amq_affecteduser'];
124 6
		}
125
126 7
		return $affectedUsers;
127
	}
128
129
	/**
130
	 * Get all items for the user we want to send an email to
131
	 *
132
	 * @param string $affectedUser
133
	 * @param int $maxTime
134
	 * @param int $maxNumItems
135
	 * @return array [data of the first max. 200 entries, total number of entries]
136
	 */
137 7
	protected function getItemsForUser($affectedUser, $maxTime, $maxNumItems = self::ENTRY_LIMIT) {
138 7
		$query = $this->connection->prepare(
139
			'SELECT * '
140
			. ' FROM `*PREFIX*activity_mq` '
141 7
			. ' WHERE `amq_timestamp` <= ? '
142 7
			. ' AND `amq_affecteduser` = ? '
143 7
			. ' ORDER BY `amq_timestamp` ASC',
144
			$maxNumItems
145 7
		);
146 7
		$query->execute([(int) $maxTime, $affectedUser]);
147
148 7
		$activities = array();
149 7
		while ($row = $query->fetch()) {
150 7
			$activities[] = $row;
151 7
		}
152
153 7
		if (isset($activities[$maxNumItems - 1])) {
154
			// Reached the limit, run a query to get the actual count.
155 1
			$query = $this->connection->prepare(
156
				'SELECT COUNT(*) AS `actual_count`'
157
				. ' FROM `*PREFIX*activity_mq` '
158 1
				. ' WHERE `amq_timestamp` <= ? '
159 1
				. ' AND `amq_affecteduser` = ?'
160 1
			);
161 1
			$query->execute([(int) $maxTime, $affectedUser]);
162
163 1
			$row = $query->fetch();
164 1
			return [$activities, $row['actual_count'] - $maxNumItems];
165
		} else {
166 7
			return [$activities, 0];
167
		}
168
	}
169
170
	/**
171
	 * Get a language object for a specific language
172
	 *
173
	 * @param string $lang Language identifier
174
	 * @return \OCP\IL10N Language object of $lang
175
	 */
176 1
	protected function getLanguage($lang) {
177 1
		if (!isset($this->languages[$lang])) {
178 1
			$this->languages[$lang] = Util::getL10N('activity', $lang);
179 1
		}
180
181 1
		return $this->languages[$lang];
182
	}
183
184
	/**
185
	 * Get the sender data
186
	 * @param string $setting Either `email` or `name`
187
	 * @return string
188
	 */
189 1
	protected function getSenderData($setting) {
190 1
		if (empty($this->senderAddress)) {
191 1
			$this->senderAddress = Util::getDefaultEmailAddress('no-reply');
192 1
		}
193 1
		if (empty($this->senderName)) {
194 1
			$defaults = new Defaults();
195 1
			$this->senderName = $defaults->getName();
196 1
		}
197
198 1
		if ($setting === 'email') {
199 1
			return $this->senderAddress;
200
		}
201 1
		return $this->senderName;
202
	}
203
204
	/**
205
	 * Validate email address
206
	 *
207
	 * @param string $email email address
208
	 * @return bool true if address is compliant, false otherwise
209
	 */
210
	public function validateMailAddress($email) {
211
		return $this->mailer->validateMailAddress($email);
212
	}
213
214
	/**
215
	 * Send a notification to one user
216
	 *
217
	 * @param string $userName Username of the recipient
218
	 * @param string $email Email address of the recipient
219
	 * @param string $lang Selected language of the recipient
220
	 * @param string $timezone Selected timezone of the recipient
221
	 * @param int $maxTime
222
	 */
223 1
	public function sendEmailToUser($userName, $email, $lang, $timezone, $maxTime) {
224 1
		$user = $this->userManager->get($userName);
225 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...
226 1
			return;
227
		}
228
229 1
		list($mailData, $skippedCount) = $this->getItemsForUser($userName, $maxTime);
230
231 1
		$l = $this->getLanguage($lang);
232 1
		$parser = new PlainTextParser($l);
233 1
		$this->dataHelper->setUser($userName);
234 1
		$this->dataHelper->setL10n($l);
235 1
		$this->activityManager->setCurrentUserId($userName);
236
237 1
		$activityList = array();
238 1
		foreach ($mailData as $activity) {
239 1
			$event = $this->activityManager->generateEvent();
240 1
			$event->setApp($activity['amq_appid'])
241 1
				->setType($activity['amq_type'])
242 1
				->setTimestamp($activity['amq_timestamp'])
243 1
				->setSubject($activity['amq_subject'], []);
244
245 1
			$relativeDateTime = $this->dateFormatter->formatDateTimeRelativeDay(
246 1
				$activity['amq_timestamp'],
247 1
				'long', 'medium',
248 1
				new \DateTimeZone($timezone), $l
249 1
			);
250
251 1
			$activityList[] = array(
252 1
				$parser->parseMessage(
253 1
					$this->dataHelper->translation(
254 1
						$activity['amq_appid'], $activity['amq_subject'], $this->dataHelper->getParameters($event, 'subject', $activity['amq_subjectparams'])
255 1
					)
256 1
				),
257 1
				$relativeDateTime,
258
			);
259 1
		}
260
261 1
		$alttext = new Template('activity', 'email.notification', '', false);
262 1
		$alttext->assign('username', $user->getDisplayName());
263 1
		$alttext->assign('activities', $activityList);
264 1
		$alttext->assign('skippedCount', $skippedCount);
265 1
		$alttext->assign('owncloud_installation', $this->urlGenerator->getAbsoluteURL('/'));
266 1
		$alttext->assign('overwriteL10N', $l);
267 1
		$emailText = $alttext->fetchPage();
268
269 1
		$message = $this->mailer->createMessage();
270 1
		$message->setTo([$email => $user->getDisplayName()]);
271 1
		$message->setSubject((string) $l->t('Activity notification'));
272 1
		$message->setPlainBody($emailText);
273 1
		$message->setFrom([$this->getSenderData('email') => $this->getSenderData('name')]);
274 1
		$this->mailer->send($message);
275
276 1
		$this->activityManager->setCurrentUserId(null);
277 1
	}
278
279
	/**
280
	 * Delete all entries we dealt with
281
	 *
282
	 * @param array $affectedUsers
283
	 * @param int $maxTime
284
	 */
285 5
	public function deleteSentItems($affectedUsers, $maxTime) {
286 5
		$placeholders = implode(',', array_fill(0, sizeof($affectedUsers), '?'));
287 5
		$queryParams = $affectedUsers;
288 5
		array_unshift($queryParams, (int) $maxTime);
289
290 5
		$query = $this->connection->prepare(
291
			'DELETE FROM `*PREFIX*activity_mq` '
292
			. ' WHERE `amq_timestamp` <= ? '
293 5
			. ' AND `amq_affecteduser` IN (' . $placeholders . ')');
294 5
		$query->execute($queryParams);
295 5
	}
296
}
297