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