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