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