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