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