Debian Codegraph @

extensions/Echo/includes/EmailBatch.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\Notifications;
4
5 use BatchRowIterator;
6 use MailAddress;
7 use MediaWiki\Extension\Notifications\Formatters\EchoHtmlDigestEmailFormatter;
8 use MediaWiki\Extension\Notifications\Formatters\EchoPlainTextDigestEmailFormatter;
9 use MediaWiki\Extension\Notifications\Mapper\EventMapper;
10 use MediaWiki\Extension\Notifications\Model\Event;
11 use MediaWiki\Language\Language;
12 use MediaWiki\Languages\LanguageFactory;
13 use MediaWiki\MediaWikiServices;
14 use MediaWiki\User\Options\UserOptionsManager;
15 use MediaWiki\User\User;
16 use stdClass;
17 use UserMailer;
18 use Wikimedia\Rdbms\IResultWrapper;
19
20 /**
21 * Handle user email batch ( daily/ weekly )
22 */
23 class EmailBatch {
24
25 /**
26 * @var User the user to be notified
27 */
28 protected $mUser;
29
30 /**
31 * @var Language
32 */
33 protected $language;
34
35 /**
36 * @var UserOptionsManager
37 */
38 protected $userOptionsManager;
39
40 /**
41 * @var Event[] events included in this email
42 */
43 protected $events = [];
44
45 /**
46 * @var Event the last notification event of this batch
47 */
48 protected $lastEvent;
49
50 /**
51 * @var int the event count, this count is supported up to self::$displaySize + 1
52 */
53 protected $count = 0;
54
55 /**
56 * @var int number of bundle events to include in an email,
57 * we cannot include all events in a batch email
58 */
59 protected static $displaySize = 20;
60
61 public function __construct(
62 User $user,
63 UserOptionsManager $userOptionsManager,
64 LanguageFactory $languageFactory
65 ) {
66 $this->mUser = $user;
67 $this->language = $languageFactory->getLanguage(
68 $userOptionsManager->getOption( $user, 'language' )
69 );
70 $this->userOptionsManager = $userOptionsManager;
71 }
72
73 /**
74 * Factory method to determine whether to create a batch instance for this
75 * user based on the user setting, this assumes the following value for
76 * member setting for echo-email-frequency
77 * -1 - no email
78 * 0 - instant
79 * 1 - once everyday
80 * 7 - once every 7 days
81 * @param int $userId
82 * @param bool $enforceFrequency Whether email sending frequency should
83 * be enforced.
84 *
85 * When true, today's notifications won't be returned if they are
86 * configured to go out tonight or at the end of the week.
87 *
88 * When false, all pending notifications will be returned.
89 * @return EmailBatch|false
90 */
91 public static function newFromUserId( $userId, $enforceFrequency = true ) {
92 $user = User::newFromId( (int)$userId );
93 $services = MediaWikiServices::getInstance();
94 $userOptionsManager = $services->getUserOptionsManager();
95 $languageFactory = $services->getLanguageFactory();
96
97 $userEmailSetting = (int)$userOptionsManager->getOption( $user, 'echo-email-frequency' );
98
99 // clear all existing events if user decides not to receive emails
100 if ( $userEmailSetting == -1 ) {
101 $emailBatch = new self( $user, $userOptionsManager, $languageFactory );
102 $emailBatch->clearProcessedEvent();
103
104 return false;
105 }
106
107 // @Todo - There may be some items idling in the queue, eg, a bundle job is lost
108 // and there is not never another message with the same hash or a user switches from
109 // digest to instant. We should check the first item in the queue, if it doesn't
110 // have either web or email bundling or created long ago, then clear it, this will
111 // prevent idling item queuing up.
112
113 // user has instant email delivery
114 if ( $userEmailSetting == 0 ) {
115 return false;
116 }
117
118 $userLastBatch = $userOptionsManager->getOption( $user, 'echo-email-last-batch' );
119
120 // send email batch, if
121 // 1. it has been long enough since last email batch based on frequency
122 // 2. there is no last batch timestamp recorded for the user
123 // 3. user has switched from batch to instant email, send events left in the queue
124 if ( $userLastBatch ) {
125 // use 20 as hours per day to get estimate
126 $nextBatch = (int)wfTimestamp( TS_UNIX, $userLastBatch ) + $userEmailSetting * 20 * 60 * 60;
127 if ( $enforceFrequency && wfTimestamp( TS_MW, $nextBatch ) > wfTimestampNow() ) {
128 return false;
129 }
130 }
131
132 return new self( $user, $userOptionsManager, $languageFactory );
133 }
134
135 /**
136 * Wrapper function that calls other functions required to process email batch
137 */
138 public function process() {
139 // if there is no event for this user, exist the process
140 if ( !$this->setLastEvent() ) {
141 return;
142 }
143
144 // get valid events
145 $events = $this->getEvents();
146
147 if ( $events ) {
148 foreach ( $events as $row ) {
149 $this->count++;
150 if ( $this->count > self::$displaySize ) {
151 break;
152 }
153 $event = Event::newFromRow( $row );
154 if ( !$event ) {
155 continue;
156 }
157 $event->setBundleHash( $row->eeb_event_hash );
158 $this->events[] = $event;
159 }
160
161 $bundler = new Bundler();
162 $this->events = $bundler->bundle( $this->events );
163
164 $this->sendEmail();
165 }
166
167 $this->clearProcessedEvent();
168 $this->updateUserLastBatchTimestamp();
169 }
170
171 /**
172 * Set the last event of this batch, this is a cutoff point for clearing
173 * processed/invalid events
174 *
175 * @return bool true if event exists false otherwise
176 */
177 protected function setLastEvent() {
178 $dbr = DbFactory::newFromDefault()->getEchoDb( DB_REPLICA );
179 $res = $dbr->newSelectQueryBuilder()
180 ->select( 'MAX( eeb_event_id )' )
181 ->from( 'echo_email_batch' )
182 ->where( [ 'eeb_user_id' => $this->mUser->getId() ] )
183 ->caller( __METHOD__ )
184 ->fetchField();
185
186 if ( $res ) {
187 $this->lastEvent = $res;
188
189 return true;
190 }
191
192 return false;
193 }
194
195 /**
196 * Update the user's last batch timestamp after a successful batch
197 */
198 protected function updateUserLastBatchTimestamp() {
199 $this->userOptionsManager->setOption(
200 $this->mUser,
201 'echo-email-last-batch',
202 wfTimestampNow()
203 );
204 $this->mUser->saveSettings();
205 $this->mUser->invalidateCache();
206 }
207
208 /**
209 * Get the events queued for the current user
210 * @return stdClass[]
211 */
212 protected function getEvents() {
213 global $wgEchoNotifications;
214
215 $events = [];
216
217 $validEvents = array_keys( $wgEchoNotifications );
218
219 // Per the tech discussion in the design meeting (03/22/2013), since this is
220 // processed by a cron job, it's okay to use GROUP BY over more complex
221 // composite index, favor insert performance, storage space over read
222 // performance in this case
223 if ( $validEvents ) {
224 $dbr = DbFactory::newFromDefault()->getEchoDb( DB_REPLICA );
225 $queryBuilder = $dbr->newSelectQueryBuilder()
226 ->select( array_merge( Event::selectFields(), [
227 'eeb_id',
228 'eeb_user_id',
229 'eeb_event_priority',
230 'eeb_event_id',
231 'eeb_event_hash',
232 ] ) )
233 ->from( 'echo_email_batch' )
234 ->join( 'echo_event', null, 'event_id = eeb_event_id' )
235 ->where( [
236 'eeb_user_id' => $this->mUser->getId(),
237 'event_type' => $validEvents
238 ] )
239 ->orderBy( 'eeb_event_priority' )
240 ->limit( self::$displaySize + 1 )
241 ->caller( __METHOD__ );
242
243 if ( $this->userOptionsManager->getOption(
244 $this->mUser, 'echo-dont-email-read-notifications'
245 ) ) {
246 $queryBuilder
247 ->join( 'echo_notification', null, 'notification_event = event_id' )
248 ->andWhere( [ 'notification_read_timestamp' => null ] );
249 }
250
251 // See setLastEvent() for more detail for this variable
252 if ( $this->lastEvent ) {
253 $queryBuilder->andWhere( $dbr->expr( 'eeb_event_id', '<=', (int)$this->lastEvent ) );
254 }
255
256 $res = $queryBuilder->fetchResultSet();
257
258 foreach ( $res as $row ) {
259 // records in the queue inserted before email bundling code
260 // have no hash, in this case, we just ignore them
261 if ( $row->eeb_event_hash ) {
262 $events[$row->eeb_id] = $row;
263 }
264 }
265 }
266
267 return $events;
268 }
269
270 /**
271 * Clear "processed" events in the queue,
272 * processed could be: email sent, invalid, users do not want to receive emails
273 */
274 public function clearProcessedEvent() {
275 global $wgUpdateRowsPerQuery;
276 $eventMapper = new EventMapper();
277 $dbFactory = DbFactory::newFromDefault();
278 $dbw = $dbFactory->getEchoDb( DB_PRIMARY );
279 $dbr = $dbFactory->getEchoDb( DB_REPLICA );
280 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
281 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
282 $domainId = $dbw->getDomainID();
283
284 $iterator = new BatchRowIterator( $dbr, 'echo_email_batch', 'eeb_event_id', $wgUpdateRowsPerQuery );
285 $iterator->addConditions( [ 'eeb_user_id' => $this->mUser->getId() ] );
286 if ( $this->lastEvent ) {
287 // There is a processed cutoff point
288 $iterator->addConditions( [ $dbr->expr( 'eeb_event_id', '<=', (int)$this->lastEvent ) ] );
289 }
290 $iterator->setCaller( __METHOD__ );
291
292 foreach ( $iterator as $batch ) {
293 $eventIds = [];
294 foreach ( $batch as $row ) {
295 $eventIds[] = $row->eeb_event_id;
296 }
297 $dbw->newDeleteQueryBuilder()
298 ->deleteFrom( 'echo_email_batch' )
299 ->where( [
300 'eeb_user_id' => $this->mUser->getId(),
301 'eeb_event_id' => $eventIds
302 ] )
303 ->caller( __METHOD__ )
304 ->execute();
305
306 // Find out which events are now orphaned, i.e. no longer referenced in echo_email_batch
307 // (besides the rows we just deleted) or in echo_notification, and delete them
308 $eventMapper->deleteOrphanedEvents( $eventIds, $this->mUser->getId(), 'echo_email_batch' );
309
310 $lbFactory->commitAndWaitForReplication(
311 __METHOD__, $ticket, [ 'domain' => $domainId ] );
312 }
313 }
314
315 /**
316 * Send the batch email
317 */
318 public function sendEmail() {
319 global $wgPasswordSender, $wgNoReplyAddress;
320
321 if ( $this->userOptionsManager->getOption( $this->mUser, 'echo-email-frequency' )
322 == EmailFrequency::WEEKLY_DIGEST
323 ) {
324 $frequency = 'weekly';
325 $emailDeliveryMode = 'weekly_digest';
326 } else {
327 $frequency = 'daily';
328 $emailDeliveryMode = 'daily_digest';
329 }
330
331 $textEmailDigestFormatter = new EchoPlainTextDigestEmailFormatter( $this->mUser, $this->language, $frequency );
332 $content = $textEmailDigestFormatter->format( $this->events, 'email' );
333
334 if ( !$content ) {
335 // no event could be formatted
336 return;
337 }
338
339 $format = NotifUser::newFromUser( $this->mUser )->getEmailFormat();
340 if ( $format == EmailFormat::HTML ) {
341 $htmlEmailDigestFormatter = new EchoHtmlDigestEmailFormatter( $this->mUser, $this->language, $frequency );
342 $htmlContent = $htmlEmailDigestFormatter->format( $this->events, 'email' );
343
344 $content = [
345 'body' => [
346 'text' => $content['body'],
347 'html' => $htmlContent['body'],
348 ],
349 'subject' => $htmlContent['subject'],
350 ];
351 }
352
353 $toAddress = MailAddress::newFromUser( $this->mUser );
354 $fromAddress = new MailAddress( $wgPasswordSender, wfMessage( 'emailsender' )->inContentLanguage()->text() );
355 $replyTo = new MailAddress( $wgNoReplyAddress );
356
357 // @Todo Push the email to job queue or just send it out directly?
358 UserMailer::send( $toAddress, $fromAddress, $content['subject'], $content['body'], [ 'replyTo' => $replyTo ] );
359 }
360
361 /**
362 * Insert notification event into email queue
363 *
364 * @param int $userId
365 * @param int $eventId
366 * @param int $priority
367 * @param string $hash
368 */
369 public static function addToQueue( $userId, $eventId, $priority, $hash ) {
370 if ( !$userId || !$eventId ) {
371 return;
372 }
373
374 $dbw = DbFactory::newFromDefault()->getEchoDb( DB_PRIMARY );
375
376 $row = [
377 'eeb_user_id' => $userId,
378 'eeb_event_id' => $eventId,
379 'eeb_event_priority' => $priority,
380 'eeb_event_hash' => $hash
381 ];
382
383 $dbw->newInsertQueryBuilder()
384 ->insertInto( 'echo_email_batch' )
385 ->ignore()
386 ->row( $row )
387 ->caller( __METHOD__ )
388 ->execute();
389 }
390
391 /**
392 * Get a list of users to be notified for the batch
393 *
394 * @param int $startUserId
395 * @param int $batchSize
396 *
397 * @return IResultWrapper
398 */
399 public static function getUsersToNotify( $startUserId, $batchSize ) {
400 $dbr = DbFactory::newFromDefault()->getEchoDb( DB_REPLICA );
401 return $dbr->newSelectQueryBuilder()
402 ->select( 'eeb_user_id' )
403 ->from( 'echo_email_batch' )
404 ->where( $dbr->expr( 'eeb_user_id', '>', (int)$startUserId ) )
405 ->orderBy( 'eeb_user_id' )
406 ->limit( $batchSize )
407 ->caller( __METHOD__ )
408 ->fetchResultSet();
409 }
410 }