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