Completed
Pull Request — master (#569)
by
unknown
04:20
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
	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
			. ' LEFT JOIN `*PREFIX*accounts` ON `user_id` = `amq_affecteduser` '
116
			. ' WHERE `amq_latest_send` < ? '
117
			. ' GROUP BY `amq_affecteduser`, `email` '
118 7
			. ' ORDER BY `amq_trigger_time` ASC',
119
			$limit);
120 7
		$query->execute(array($latestSend));
121
122 7
		$affectedUsers = array();
123 7
		while ($row = $query->fetch()) {
124 6
			$affectedUsers[] = [
125 6
				'uid' => $row['amq_affecteduser'],
126 6
				'email' => $row['email']
127
			];
128
		}
129
130 7
		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 7
	protected function getItemsForUser($affectedUser, $maxTime, $maxNumItems = self::ENTRY_LIMIT) {
142 7
		$query = $this->connection->prepare(
143
			'SELECT * '
144
			. ' FROM `*PREFIX*activity_mq` '
145
			. ' WHERE `amq_timestamp` <= ? '
146
			. ' AND `amq_affecteduser` = ? '
147 7
			. ' ORDER BY `amq_timestamp` ASC',
148
			$maxNumItems
149
		);
150 7
		$query->execute([(int) $maxTime, $affectedUser]);
151
152 7
		$activities = array();
153 7
		while ($row = $query->fetch()) {
154 7
			$activities[] = $row;
155
		}
156
157 7
		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 7
			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 1
	protected function getLanguage($lang) {
181 1
		if (!isset($this->languages[$lang])) {
182 1
			$this->languages[$lang] = Util::getL10N('activity', $lang);
183
		}
184
185 1
		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 1
	protected function getSenderData($setting) {
194 1
		if (empty($this->senderAddress)) {
195 1
			$this->senderAddress = Util::getDefaultEmailAddress('no-reply');
196
		}
197 1
		if (empty($this->senderName)) {
198 1
			$defaults = new Defaults();
199 1
			$this->senderName = $defaults->getName();
200
		}
201
202 1
		if ($setting === 'email') {
203 1
			return $this->senderAddress;
204
		}
205 1
		return $this->senderName;
206
	}
207
208
	/**
209
	 * Validate email address
210
	 *
211
	 * @param string $email email address
212
	 * @return bool true if address is compliant, false otherwise
213
	 */
214
	public function validateMailAddress($email) {
215
		return $this->mailer->validateMailAddress($email);
216
	}
217
218
	/**
219
	 * Send a notification to one user
220
	 *
221
	 * @param string $userName Username of the recipient
222
	 * @param string $email Email address of the recipient
223
	 * @param string $lang Selected language of the recipient
224
	 * @param string $timezone Selected timezone of the recipient
225
	 * @param int $maxTime
226
	 */
227 1
	public function sendEmailToUser($userName, $email, $lang, $timezone, $maxTime) {
228 1
		$user = $this->userManager->get($userName);
229 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...
230 1
			return;
231
		}
232
233 1
		list($mailData, $skippedCount) = $this->getItemsForUser($userName, $maxTime);
234
235 1
		$l = $this->getLanguage($lang);
236 1
		$parser = new PlainTextParser($l);
237 1
		$this->dataHelper->setUser($userName);
238 1
		$this->dataHelper->setL10n($l);
239 1
		$this->activityManager->setCurrentUserId($userName);
240
241 1
		$activityList = array();
242 1
		foreach ($mailData as $activity) {
243 1
			$event = $this->activityManager->generateEvent();
244 1
			$event->setApp($activity['amq_appid'])
245 1
				->setType($activity['amq_type'])
246 1
				->setTimestamp($activity['amq_timestamp'])
247 1
				->setSubject($activity['amq_subject'], []);
248
249 1
			$relativeDateTime = $this->dateFormatter->formatDateTimeRelativeDay(
250 1
				$activity['amq_timestamp'],
251 1
				'long', 'medium',
252 1
				new \DateTimeZone($timezone), $l
253
			);
254
255 1
			$activityList[] = array(
256 1
				$parser->parseMessage(
257 1
					$this->dataHelper->translation(
258 1
						$activity['amq_appid'], $activity['amq_subject'], $this->dataHelper->getParameters($event, 'subject', $activity['amq_subjectparams'])
259
					)
260
				),
261 1
				$relativeDateTime,
262
			);
263
		}
264
265 1
		$alttext = new Template('activity', 'email.notification', '', false);
266 1
		$alttext->assign('username', $user->getDisplayName());
267 1
		$alttext->assign('activities', $activityList);
268 1
		$alttext->assign('skippedCount', $skippedCount);
269 1
		$alttext->assign('owncloud_installation', $this->urlGenerator->getAbsoluteURL('/'));
270 1
		$alttext->assign('overwriteL10N', $l);
271 1
		$emailText = $alttext->fetchPage();
272
273 1
		$message = $this->mailer->createMessage();
274 1
		$message->setTo([$email => $user->getDisplayName()]);
275 1
		$message->setSubject((string) $l->t('Activity notification'));
276 1
		$message->setPlainBody($emailText);
277 1
		$message->setFrom([$this->getSenderData('email') => $this->getSenderData('name')]);
278 1
		$this->mailer->send($message);
279
280 1
		$this->activityManager->setCurrentUserId(null);
281 1
	}
282
283
	/**
284
	 * Delete all entries we dealt with
285
	 *
286
	 * @param array $affectedUsers
287
	 * @param int $maxTime
288
	 */
289 5
	public function deleteSentItems($affectedUsers, $maxTime) {
290 5
		$placeholders = implode(',', array_fill(0, sizeof($affectedUsers), '?'));
291 5
		$queryParams = $affectedUsers;
292 5
		array_unshift($queryParams, (int) $maxTime);
293
294 5
		$query = $this->connection->prepare(
295
			'DELETE FROM `*PREFIX*activity_mq` '
296
			. ' WHERE `amq_timestamp` <= ? '
297 5
			. ' AND `amq_affecteduser` IN (' . $placeholders . ')');
298 5
		$query->execute($queryParams);
299 5
	}
300
}
301