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