Merge "Use LinkTarget in EmailNotification::updateWatchlistTimestamp"
[lhc/web/wiklou.git] / includes / mail / EmailNotification.php
1 <?php
2 /**
3 * Classes used to send e-mails
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @author <brion@pobox.com>
22 * @author <mail@tgries.de>
23 * @author Tim Starling
24 * @author Luke Welling lwelling@wikimedia.org
25 */
26
27 /**
28 * This module processes the email notifications when the current page is
29 * changed. It looks up the table watchlist to find out which users are watching
30 * that page.
31 *
32 * The current implementation sends independent emails to each watching user for
33 * the following reason:
34 *
35 * - Each watching user will be notified about the page edit time expressed in
36 * his/her local time (UTC is shown additionally). To achieve this, we need to
37 * find the individual timeoffset of each watching user from the preferences..
38 *
39 * Suggested improvement to slack down the number of sent emails: We could think
40 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
41 * same timeoffset in their preferences.
42 *
43 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
44 */
45 class EmailNotification {
46
47 /**
48 * Notification is due to user's user talk being edited
49 */
50 const USER_TALK = 'user_talk';
51 /**
52 * Notification is due to a watchlisted page being edited
53 */
54 const WATCHLIST = 'watchlist';
55 /**
56 * Notification because user is notified for all changes
57 */
58 const ALL_CHANGES = 'all_changes';
59
60 protected $subject, $body, $replyto, $from;
61 protected $timestamp, $summary, $minorEdit, $oldid, $composed_common, $pageStatus;
62 protected $mailTargets = array();
63
64 /**
65 * @var Title
66 */
67 protected $title;
68
69 /**
70 * @var User
71 */
72 protected $editor;
73
74 /**
75 * @param User $editor The editor that triggered the update. Their notification
76 * timestamp will not be updated(they have already seen it)
77 * @param LinkTarget $linkTarget The link target of the title to update timestamps for
78 * @param string $timestamp Set the update timestamp to this value
79 * @return int[] Array of user IDs
80 */
81 public static function updateWatchlistTimestamp(
82 User $editor,
83 LinkTarget $linkTarget,
84 $timestamp
85 ) {
86 global $wgEnotifWatchlist, $wgShowUpdatedMarker;
87
88 if ( !$wgEnotifWatchlist && !$wgShowUpdatedMarker ) {
89 return array();
90 }
91
92 $dbw = wfGetDB( DB_MASTER );
93 $res = $dbw->select( array( 'watchlist' ),
94 array( 'wl_user' ),
95 array(
96 'wl_user != ' . intval( $editor->getID() ),
97 'wl_namespace' => $linkTarget->getNamespace(),
98 'wl_title' => $linkTarget->getDBkey(),
99 'wl_notificationtimestamp IS NULL',
100 ), __METHOD__
101 );
102
103 $watchers = array();
104 foreach ( $res as $row ) {
105 $watchers[] = intval( $row->wl_user );
106 }
107
108 if ( $watchers ) {
109 // Update wl_notificationtimestamp for all watching users except the editor
110 $fname = __METHOD__;
111 $dbw->onTransactionIdle(
112 function () use ( $dbw, $timestamp, $watchers, $linkTarget, $fname ) {
113 $dbw->update( 'watchlist',
114 array( /* SET */
115 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
116 ), array( /* WHERE */
117 'wl_user' => $watchers,
118 'wl_namespace' => $linkTarget->getNamespace(),
119 'wl_title' => $linkTarget->getDBkey(),
120 ), $fname
121 );
122 }
123 );
124 }
125
126 return $watchers;
127 }
128
129 /**
130 * Send emails corresponding to the user $editor editing the page $title.
131 *
132 * May be deferred via the job queue.
133 *
134 * @param User $editor
135 * @param Title $title
136 * @param string $timestamp
137 * @param string $summary
138 * @param bool $minorEdit
139 * @param bool $oldid (default: false)
140 * @param string $pageStatus (default: 'changed')
141 */
142 public function notifyOnPageChange( $editor, $title, $timestamp, $summary,
143 $minorEdit, $oldid = false, $pageStatus = 'changed'
144 ) {
145 global $wgEnotifMinorEdits, $wgUsersNotifiedOnAllChanges, $wgEnotifUserTalk;
146
147 if ( $title->getNamespace() < 0 ) {
148 return;
149 }
150
151 // update wl_notificationtimestamp for watchers
152 $watchers = self::updateWatchlistTimestamp( $editor, $title, $timestamp );
153
154 $sendEmail = true;
155 // $watchers deals with $wgEnotifWatchlist.
156 // If nobody is watching the page, and there are no users notified on all changes
157 // don't bother creating a job/trying to send emails, unless it's a
158 // talk page with an applicable notification.
159 if ( !count( $watchers ) && !count( $wgUsersNotifiedOnAllChanges ) ) {
160 $sendEmail = false;
161 // Only send notification for non minor edits, unless $wgEnotifMinorEdits
162 if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
163 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
164 if ( $wgEnotifUserTalk
165 && $isUserTalkPage
166 && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
167 ) {
168 $sendEmail = true;
169 }
170 }
171 }
172
173 if ( $sendEmail ) {
174 JobQueueGroup::singleton()->lazyPush( new EnotifNotifyJob(
175 $title,
176 array(
177 'editor' => $editor->getName(),
178 'editorID' => $editor->getID(),
179 'timestamp' => $timestamp,
180 'summary' => $summary,
181 'minorEdit' => $minorEdit,
182 'oldid' => $oldid,
183 'watchers' => $watchers,
184 'pageStatus' => $pageStatus
185 )
186 ) );
187 }
188 }
189
190 /**
191 * Immediate version of notifyOnPageChange().
192 *
193 * Send emails corresponding to the user $editor editing the page $title.
194 *
195 * @note Do not call directly. Use notifyOnPageChange so that wl_notificationtimestamp is updated.
196 * @param User $editor
197 * @param Title $title
198 * @param string $timestamp Edit timestamp
199 * @param string $summary Edit summary
200 * @param bool $minorEdit
201 * @param int $oldid Revision ID
202 * @param array $watchers Array of user IDs
203 * @param string $pageStatus
204 * @throws MWException
205 */
206 public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit,
207 $oldid, $watchers, $pageStatus = 'changed' ) {
208 # we use $wgPasswordSender as sender's address
209 global $wgUsersNotifiedOnAllChanges;
210 global $wgEnotifWatchlist, $wgBlockDisablesLogin;
211 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
212
213 # The following code is only run, if several conditions are met:
214 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
215 # 2. minor edits (changes) are only regarded if the global flag indicates so
216
217 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
218
219 $this->title = $title;
220 $this->timestamp = $timestamp;
221 $this->summary = $summary;
222 $this->minorEdit = $minorEdit;
223 $this->oldid = $oldid;
224 $this->editor = $editor;
225 $this->composed_common = false;
226 $this->pageStatus = $pageStatus;
227
228 $formattedPageStatus = array( 'deleted', 'created', 'moved', 'restored', 'changed' );
229
230 Hooks::run( 'UpdateUserMailerFormattedPageStatus', array( &$formattedPageStatus ) );
231 if ( !in_array( $this->pageStatus, $formattedPageStatus ) ) {
232 throw new MWException( 'Not a valid page status!' );
233 }
234
235 $userTalkId = false;
236
237 if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
238 if ( $wgEnotifUserTalk
239 && $isUserTalkPage
240 && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
241 ) {
242 $targetUser = User::newFromName( $title->getText() );
243 $this->compose( $targetUser, self::USER_TALK );
244 $userTalkId = $targetUser->getId();
245 }
246
247 if ( $wgEnotifWatchlist ) {
248 // Send updates to watchers other than the current editor
249 // and don't send to watchers who are blocked and cannot login
250 $userArray = UserArray::newFromIDs( $watchers );
251 foreach ( $userArray as $watchingUser ) {
252 if ( $watchingUser->getOption( 'enotifwatchlistpages' )
253 && ( !$minorEdit || $watchingUser->getOption( 'enotifminoredits' ) )
254 && $watchingUser->isEmailConfirmed()
255 && $watchingUser->getID() != $userTalkId
256 && !in_array( $watchingUser->getName(), $wgUsersNotifiedOnAllChanges )
257 && !( $wgBlockDisablesLogin && $watchingUser->isBlocked() )
258 ) {
259 if ( Hooks::run( 'SendWatchlistEmailNotification', array( $watchingUser, $title, $this ) ) ) {
260 $this->compose( $watchingUser, self::WATCHLIST );
261 }
262 }
263 }
264 }
265 }
266
267 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
268 if ( $editor->getName() == $name ) {
269 // No point notifying the user that actually made the change!
270 continue;
271 }
272 $user = User::newFromName( $name );
273 $this->compose( $user, self::ALL_CHANGES );
274 }
275
276 $this->sendMails();
277 }
278
279 /**
280 * @param User $editor
281 * @param Title $title
282 * @param bool $minorEdit
283 * @return bool
284 */
285 private function canSendUserTalkEmail( $editor, $title, $minorEdit ) {
286 global $wgEnotifUserTalk, $wgBlockDisablesLogin;
287 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
288
289 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
290 $targetUser = User::newFromName( $title->getText() );
291
292 if ( !$targetUser || $targetUser->isAnon() ) {
293 wfDebug( __METHOD__ . ": user talk page edited, but user does not exist\n" );
294 } elseif ( $targetUser->getId() == $editor->getId() ) {
295 wfDebug( __METHOD__ . ": user edited their own talk page, no notification sent\n" );
296 } elseif ( $wgBlockDisablesLogin && $targetUser->isBlocked() ) {
297 wfDebug( __METHOD__ . ": talk page owner is blocked and cannot login, no notification sent\n" );
298 } elseif ( $targetUser->getOption( 'enotifusertalkpages' )
299 && ( !$minorEdit || $targetUser->getOption( 'enotifminoredits' ) )
300 ) {
301 if ( !$targetUser->isEmailConfirmed() ) {
302 wfDebug( __METHOD__ . ": talk page owner doesn't have validated email\n" );
303 } elseif ( !Hooks::run( 'AbortTalkPageEmailNotification', array( $targetUser, $title ) ) ) {
304 wfDebug( __METHOD__ . ": talk page update notification is aborted for this user\n" );
305 } else {
306 wfDebug( __METHOD__ . ": sending talk page update notification\n" );
307 return true;
308 }
309 } else {
310 wfDebug( __METHOD__ . ": talk page owner doesn't want notifications\n" );
311 }
312 }
313 return false;
314 }
315
316 /**
317 * Generate the generic "this page has been changed" e-mail text.
318 */
319 private function composeCommonMailtext() {
320 global $wgPasswordSender, $wgNoReplyAddress;
321 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
322 global $wgEnotifImpersonal, $wgEnotifUseRealName;
323
324 $this->composed_common = true;
325
326 # You as the WikiAdmin and Sysops can make use of plenty of
327 # named variables when composing your notification emails while
328 # simply editing the Meta pages
329
330 $keys = array();
331 $postTransformKeys = array();
332 $pageTitleUrl = $this->title->getCanonicalURL();
333 $pageTitle = $this->title->getPrefixedText();
334
335 if ( $this->oldid ) {
336 // Always show a link to the diff which triggered the mail. See bug 32210.
337 $keys['$NEWPAGE'] = "\n\n" . wfMessage( 'enotif_lastdiff',
338 $this->title->getCanonicalURL( array( 'diff' => 'next', 'oldid' => $this->oldid ) ) )
339 ->inContentLanguage()->text();
340
341 if ( !$wgEnotifImpersonal ) {
342 // For personal mail, also show a link to the diff of all changes
343 // since last visited.
344 $keys['$NEWPAGE'] .= "\n\n" . wfMessage( 'enotif_lastvisited',
345 $this->title->getCanonicalURL( array( 'diff' => '0', 'oldid' => $this->oldid ) ) )
346 ->inContentLanguage()->text();
347 }
348 $keys['$OLDID'] = $this->oldid;
349 // Deprecated since MediaWiki 1.21, not used by default. Kept for backwards-compatibility.
350 $keys['$CHANGEDORCREATED'] = wfMessage( 'changed' )->inContentLanguage()->text();
351 } else {
352 # clear $OLDID placeholder in the message template
353 $keys['$OLDID'] = '';
354 $keys['$NEWPAGE'] = '';
355 // Deprecated since MediaWiki 1.21, not used by default. Kept for backwards-compatibility.
356 $keys['$CHANGEDORCREATED'] = wfMessage( 'created' )->inContentLanguage()->text();
357 }
358
359 $keys['$PAGETITLE'] = $this->title->getPrefixedText();
360 $keys['$PAGETITLE_URL'] = $this->title->getCanonicalURL();
361 $keys['$PAGEMINOREDIT'] = $this->minorEdit ?
362 wfMessage( 'minoredit' )->inContentLanguage()->text() : '';
363 $keys['$UNWATCHURL'] = $this->title->getCanonicalURL( 'action=unwatch' );
364
365 if ( $this->editor->isAnon() ) {
366 # real anon (user:xxx.xxx.xxx.xxx)
367 $keys['$PAGEEDITOR'] = wfMessage( 'enotif_anon_editor', $this->editor->getName() )
368 ->inContentLanguage()->text();
369 $keys['$PAGEEDITOR_EMAIL'] = wfMessage( 'noemailtitle' )->inContentLanguage()->text();
370
371 } else {
372 $keys['$PAGEEDITOR'] = $wgEnotifUseRealName && $this->editor->getRealName() !== ''
373 ? $this->editor->getRealName() : $this->editor->getName();
374 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $this->editor->getName() );
375 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getCanonicalURL();
376 }
377
378 $keys['$PAGEEDITOR_WIKI'] = $this->editor->getUserPage()->getCanonicalURL();
379 $keys['$HELPPAGE'] = wfExpandUrl(
380 Skin::makeInternalOrExternalUrl( wfMessage( 'helppage' )->inContentLanguage()->text() )
381 );
382
383 # Replace this after transforming the message, bug 35019
384 $postTransformKeys['$PAGESUMMARY'] = $this->summary == '' ? ' - ' : $this->summary;
385
386 // Now build message's subject and body
387
388 // Messages:
389 // enotif_subject_deleted, enotif_subject_created, enotif_subject_moved,
390 // enotif_subject_restored, enotif_subject_changed
391 $this->subject = wfMessage( 'enotif_subject_' . $this->pageStatus )->inContentLanguage()
392 ->params( $pageTitle, $keys['$PAGEEDITOR'] )->text();
393
394 // Messages:
395 // enotif_body_intro_deleted, enotif_body_intro_created, enotif_body_intro_moved,
396 // enotif_body_intro_restored, enotif_body_intro_changed
397 $keys['$PAGEINTRO'] = wfMessage( 'enotif_body_intro_' . $this->pageStatus )
398 ->inContentLanguage()->params( $pageTitle, $keys['$PAGEEDITOR'], $pageTitleUrl )
399 ->text();
400
401 $body = wfMessage( 'enotif_body' )->inContentLanguage()->plain();
402 $body = strtr( $body, $keys );
403 $body = MessageCache::singleton()->transform( $body, false, null, $this->title );
404 $this->body = wordwrap( strtr( $body, $postTransformKeys ), 72 );
405
406 # Reveal the page editor's address as REPLY-TO address only if
407 # the user has not opted-out and the option is enabled at the
408 # global configuration level.
409 $adminAddress = new MailAddress( $wgPasswordSender,
410 wfMessage( 'emailsender' )->inContentLanguage()->text() );
411 if ( $wgEnotifRevealEditorAddress
412 && ( $this->editor->getEmail() != '' )
413 && $this->editor->getOption( 'enotifrevealaddr' )
414 ) {
415 $editorAddress = MailAddress::newFromUser( $this->editor );
416 if ( $wgEnotifFromEditor ) {
417 $this->from = $editorAddress;
418 } else {
419 $this->from = $adminAddress;
420 $this->replyto = $editorAddress;
421 }
422 } else {
423 $this->from = $adminAddress;
424 $this->replyto = new MailAddress( $wgNoReplyAddress );
425 }
426 }
427
428 /**
429 * Compose a mail to a given user and either queue it for sending, or send it now,
430 * depending on settings.
431 *
432 * Call sendMails() to send any mails that were queued.
433 * @param User $user
434 * @param string $source
435 */
436 function compose( $user, $source ) {
437 global $wgEnotifImpersonal;
438
439 if ( !$this->composed_common ) {
440 $this->composeCommonMailtext();
441 }
442
443 if ( $wgEnotifImpersonal ) {
444 $this->mailTargets[] = MailAddress::newFromUser( $user );
445 } else {
446 $this->sendPersonalised( $user, $source );
447 }
448 }
449
450 /**
451 * Send any queued mails
452 */
453 function sendMails() {
454 global $wgEnotifImpersonal;
455 if ( $wgEnotifImpersonal ) {
456 $this->sendImpersonal( $this->mailTargets );
457 }
458 }
459
460 /**
461 * Does the per-user customizations to a notification e-mail (name,
462 * timestamp in proper timezone, etc) and sends it out.
463 * Returns true if the mail was sent successfully.
464 *
465 * @param User $watchingUser
466 * @param string $source
467 * @return bool
468 * @private
469 */
470 function sendPersonalised( $watchingUser, $source ) {
471 global $wgContLang, $wgEnotifUseRealName;
472 // From the PHP manual:
473 // Note: The to parameter cannot be an address in the form of
474 // "Something <someone@example.com>". The mail command will not parse
475 // this properly while talking with the MTA.
476 $to = MailAddress::newFromUser( $watchingUser );
477
478 # $PAGEEDITDATE is the time and date of the page change
479 # expressed in terms of individual local time of the notification
480 # recipient, i.e. watching user
481 $body = str_replace(
482 array( '$WATCHINGUSERNAME',
483 '$PAGEEDITDATE',
484 '$PAGEEDITTIME' ),
485 array( $wgEnotifUseRealName && $watchingUser->getRealName() !== ''
486 ? $watchingUser->getRealName() : $watchingUser->getName(),
487 $wgContLang->userDate( $this->timestamp, $watchingUser ),
488 $wgContLang->userTime( $this->timestamp, $watchingUser ) ),
489 $this->body );
490
491 $headers = array();
492 if ( $source === self::WATCHLIST ) {
493 $headers['List-Help'] = 'https://www.mediawiki.org/wiki/Special:MyLanguage/Help:Watchlist';
494 }
495
496 return UserMailer::send( $to, $this->from, $this->subject, $body, array(
497 'replyTo' => $this->replyto,
498 'headers' => $headers,
499 ) );
500 }
501
502 /**
503 * Same as sendPersonalised but does impersonal mail suitable for bulk
504 * mailing. Takes an array of MailAddress objects.
505 * @param MailAddress[] $addresses
506 * @return Status|null
507 */
508 function sendImpersonal( $addresses ) {
509 global $wgContLang;
510
511 if ( empty( $addresses ) ) {
512 return null;
513 }
514
515 $body = str_replace(
516 array( '$WATCHINGUSERNAME',
517 '$PAGEEDITDATE',
518 '$PAGEEDITTIME' ),
519 array( wfMessage( 'enotif_impersonal_salutation' )->inContentLanguage()->text(),
520 $wgContLang->date( $this->timestamp, false, false ),
521 $wgContLang->time( $this->timestamp, false, false ) ),
522 $this->body );
523
524 return UserMailer::send( $addresses, $this->from, $this->subject, $body, array(
525 'replyTo' => $this->replyto,
526 ) );
527 }
528
529 }