Merge "Avoid extra parsing in prepareContentForEdit()"
[lhc/web/wiklou.git] / includes / UserMailer.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 * Stores a single person's name and email address.
29 * These are passed in via the constructor, and will be returned in SMTP
30 * header format when requested.
31 */
32 class MailAddress {
33 /**
34 * @param string|User $address string with an email address, or a User object
35 * @param string $name human-readable name if a string address is given
36 * @param string $realName human-readable real name if a string address is given
37 */
38 function __construct( $address, $name = null, $realName = null ) {
39 if ( is_object( $address ) && $address instanceof User ) {
40 $this->address = $address->getEmail();
41 $this->name = $address->getName();
42 $this->realName = $address->getRealName();
43 } else {
44 $this->address = strval( $address );
45 $this->name = strval( $name );
46 $this->realName = strval( $realName );
47 }
48 }
49
50 /**
51 * Return formatted and quoted address to insert into SMTP headers
52 * @return string
53 */
54 function toString() {
55 # PHP's mail() implementation under Windows is somewhat shite, and
56 # can't handle "Joe Bloggs <joe@bloggs.com>" format email addresses,
57 # so don't bother generating them
58 if ( $this->address ) {
59 if ( $this->name != '' && !wfIsWindows() ) {
60 global $wgEnotifUseRealName;
61 $name = ( $wgEnotifUseRealName && $this->realName ) ? $this->realName : $this->name;
62 $quoted = UserMailer::quotedPrintable( $name );
63 if ( strpos( $quoted, '.' ) !== false || strpos( $quoted, ',' ) !== false ) {
64 $quoted = '"' . $quoted . '"';
65 }
66 return "$quoted <{$this->address}>";
67 } else {
68 return $this->address;
69 }
70 } else {
71 return "";
72 }
73 }
74
75 function __toString() {
76 return $this->toString();
77 }
78 }
79
80 /**
81 * Collection of static functions for sending mail
82 */
83 class UserMailer {
84 static $mErrorString;
85
86 /**
87 * Send mail using a PEAR mailer
88 *
89 * @param $mailer
90 * @param $dest
91 * @param $headers
92 * @param $body
93 *
94 * @return Status
95 */
96 protected static function sendWithPear( $mailer, $dest, $headers, $body ) {
97 $mailResult = $mailer->send( $dest, $headers, $body );
98
99 # Based on the result return an error string,
100 if ( PEAR::isError( $mailResult ) ) {
101 wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
102 return Status::newFatal( 'pear-mail-error', $mailResult->getMessage() );
103 } else {
104 return Status::newGood();
105 }
106 }
107
108 /**
109 * Creates a single string from an associative array
110 *
111 * @param array $headers Associative Array: keys are header field names,
112 * values are ... values.
113 * @param string $endl The end of line character. Defaults to "\n"
114 *
115 * Note RFC2822 says newlines must be CRLF (\r\n)
116 * but php mail naively "corrects" it and requires \n for the "correction" to work
117 *
118 * @return String
119 */
120 static function arrayToHeaderString( $headers, $endl = "\n" ) {
121 $strings = array();
122 foreach ( $headers as $name => $value ) {
123 $strings[] = "$name: $value";
124 }
125 return implode( $endl, $strings );
126 }
127
128 /**
129 * Create a value suitable for the MessageId Header
130 *
131 * @return String
132 */
133 static function makeMsgId() {
134 global $wgSMTP, $wgServer;
135
136 $msgid = uniqid( wfWikiID() . ".", true ); /* true required for cygwin */
137 if ( is_array( $wgSMTP ) && isset( $wgSMTP['IDHost'] ) && $wgSMTP['IDHost'] ) {
138 $domain = $wgSMTP['IDHost'];
139 } else {
140 $url = wfParseUrl( $wgServer );
141 $domain = $url['host'];
142 }
143 return "<$msgid@$domain>";
144 }
145
146 /**
147 * This function will perform a direct (authenticated) login to
148 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
149 * array of parameters. It requires PEAR:Mail to do that.
150 * Otherwise it just uses the standard PHP 'mail' function.
151 *
152 * @param $to MailAddress: recipient's email (or an array of them)
153 * @param $from MailAddress: sender's email
154 * @param string $subject email's subject.
155 * @param string $body email's text or Array of two strings to be the text and html bodies
156 * @param $replyto MailAddress: optional reply-to email (default: null).
157 * @param string $contentType optional custom Content-Type (default: text/plain; charset=UTF-8)
158 * @throws MWException
159 * @return Status object
160 */
161 public static function send( $to, $from, $subject, $body, $replyto = null, $contentType = 'text/plain; charset=UTF-8' ) {
162 global $wgSMTP, $wgEnotifMaxRecips, $wgAdditionalMailParams, $wgAllowHTMLEmail;
163 $mime = null;
164 if ( !is_array( $to ) ) {
165 $to = array( $to );
166 }
167
168 // mail body must have some content
169 $minBodyLen = 10;
170 // arbitrary but longer than Array or Object to detect casting error
171
172 // body must either be a string or an array with text and body
173 if (
174 !(
175 !is_array( $body ) &&
176 strlen( $body ) >= $minBodyLen
177 )
178 &&
179 !(
180 is_array( $body ) &&
181 isset( $body['text'] ) &&
182 isset( $body['html'] ) &&
183 strlen( $body['text'] ) >= $minBodyLen &&
184 strlen( $body['html'] ) >= $minBodyLen
185 )
186 ) {
187 // if it is neither we have a problem
188 return Status::newFatal( 'user-mail-no-body' );
189 }
190
191 if ( !$wgAllowHTMLEmail && is_array( $body ) ) {
192 // HTML not wanted. Dump it.
193 $body = $body['text'];
194 }
195
196 wfDebug( __METHOD__ . ': sending mail to ' . implode( ', ', $to ) . "\n" );
197
198 # Make sure we have at least one address
199 $has_address = false;
200 foreach ( $to as $u ) {
201 if ( $u->address ) {
202 $has_address = true;
203 break;
204 }
205 }
206 if ( !$has_address ) {
207 return Status::newFatal( 'user-mail-no-addy' );
208 }
209
210 # Forge email headers
211 # -------------------
212 #
213 # WARNING
214 #
215 # DO NOT add To: or Subject: headers at this step. They need to be
216 # handled differently depending upon the mailer we are going to use.
217 #
218 # To:
219 # PHP mail() first argument is the mail receiver. The argument is
220 # used as a recipient destination and as a To header.
221 #
222 # PEAR mailer has a recipient argument which is only used to
223 # send the mail. If no To header is given, PEAR will set it to
224 # to 'undisclosed-recipients:'.
225 #
226 # NOTE: To: is for presentation, the actual recipient is specified
227 # by the mailer using the Rcpt-To: header.
228 #
229 # Subject:
230 # PHP mail() second argument to pass the subject, passing a Subject
231 # as an additional header will result in a duplicate header.
232 #
233 # PEAR mailer should be passed a Subject header.
234 #
235 # -- hashar 20120218
236
237 $headers['From'] = $from->toString();
238 $headers['Return-Path'] = $from->address;
239
240 if ( $replyto ) {
241 $headers['Reply-To'] = $replyto->toString();
242 }
243
244 $headers['Date'] = MWTimestamp::getLocalInstance()->format( 'r' );
245 $headers['Message-ID'] = self::makeMsgId();
246 $headers['X-Mailer'] = 'MediaWiki mailer';
247
248 # Line endings need to be different on Unix and Windows due to
249 # the bug described at http://trac.wordpress.org/ticket/2603
250 if ( wfIsWindows() ) {
251 $endl = "\r\n";
252 } else {
253 $endl = "\n";
254 }
255
256 if ( is_array( $body ) ) {
257 // we are sending a multipart message
258 wfDebug( "Assembling multipart mime email\n" );
259 if ( !stream_resolve_include_path( 'Mail/mime.php' ) ) {
260 wfDebug( "PEAR Mail_Mime package is not installed. Falling back to text email.\n" );
261 // remove the html body for text email fall back
262 $body = $body['text'];
263 }
264 else {
265 require_once 'Mail/mime.php';
266 if ( wfIsWindows() ) {
267 $body['text'] = str_replace( "\n", "\r\n", $body['text'] );
268 $body['html'] = str_replace( "\n", "\r\n", $body['html'] );
269 }
270 $mime = new Mail_mime( array( 'eol' => $endl, 'text_charset' => 'UTF-8', 'html_charset' => 'UTF-8' ) );
271 $mime->setTXTBody( $body['text'] );
272 $mime->setHTMLBody( $body['html'] );
273 $body = $mime->get(); // must call get() before headers()
274 $headers = $mime->headers( $headers );
275 }
276 }
277 if ( !isset( $mime ) ) {
278 // sending text only, either deliberately or as a fallback
279 if ( wfIsWindows() ) {
280 $body = str_replace( "\n", "\r\n", $body );
281 }
282 $headers['MIME-Version'] = '1.0';
283 $headers['Content-type'] = ( is_null( $contentType ) ?
284 'text/plain; charset=UTF-8' : $contentType );
285 $headers['Content-transfer-encoding'] = '8bit';
286 }
287
288 $ret = wfRunHooks( 'AlternateUserMailer', array( $headers, $to, $from, $subject, $body ) );
289 if ( $ret === false ) {
290 // the hook implementation will return false to skip regular mail sending
291 return Status::newGood();
292 } elseif ( $ret !== true ) {
293 // the hook implementation will return a string to pass an error message
294 return Status::newFatal( 'php-mail-error', $ret );
295 }
296
297 if ( is_array( $wgSMTP ) ) {
298 #
299 # PEAR MAILER
300 #
301
302 if ( !stream_resolve_include_path( 'Mail.php' ) ) {
303 throw new MWException( 'PEAR mail package is not installed' );
304 }
305 require_once 'Mail.php';
306
307 wfSuppressWarnings();
308
309 // Create the mail object using the Mail::factory method
310 $mail_object =& Mail::factory( 'smtp', $wgSMTP );
311 if ( PEAR::isError( $mail_object ) ) {
312 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
313 wfRestoreWarnings();
314 return Status::newFatal( 'pear-mail-error', $mail_object->getMessage() );
315 }
316
317 wfDebug( "Sending mail via PEAR::Mail\n" );
318
319 $headers['Subject'] = self::quotedPrintable( $subject );
320
321 # When sending only to one recipient, shows it its email using To:
322 if ( count( $to ) == 1 ) {
323 $headers['To'] = $to[0]->toString();
324 }
325
326 # Split jobs since SMTP servers tends to limit the maximum
327 # number of possible recipients.
328 $chunks = array_chunk( $to, $wgEnotifMaxRecips );
329 foreach ( $chunks as $chunk ) {
330 $status = self::sendWithPear( $mail_object, $chunk, $headers, $body );
331 # FIXME : some chunks might be sent while others are not!
332 if ( !$status->isOK() ) {
333 wfRestoreWarnings();
334 return $status;
335 }
336 }
337 wfRestoreWarnings();
338 return Status::newGood();
339 } else {
340 #
341 # PHP mail()
342 #
343 if ( count( $to ) > 1 ) {
344 $headers['To'] = 'undisclosed-recipients:;';
345 }
346 $headers = self::arrayToHeaderString( $headers, $endl );
347
348 wfDebug( "Sending mail via internal mail() function\n" );
349
350 self::$mErrorString = '';
351 $html_errors = ini_get( 'html_errors' );
352 ini_set( 'html_errors', '0' );
353 set_error_handler( 'UserMailer::errorHandler' );
354
355 try {
356 $safeMode = wfIniGetBool( 'safe_mode' );
357
358 foreach ( $to as $recip ) {
359 if ( $safeMode ) {
360 $sent = mail( $recip, self::quotedPrintable( $subject ), $body, $headers );
361 } else {
362 $sent = mail( $recip, self::quotedPrintable( $subject ), $body, $headers, $wgAdditionalMailParams );
363 }
364 }
365 } catch ( Exception $e ) {
366 restore_error_handler();
367 throw $e;
368 }
369
370 restore_error_handler();
371 ini_set( 'html_errors', $html_errors );
372
373 if ( self::$mErrorString ) {
374 wfDebug( "Error sending mail: " . self::$mErrorString . "\n" );
375 return Status::newFatal( 'php-mail-error', self::$mErrorString );
376 } elseif ( ! $sent ) {
377 // mail function only tells if there's an error
378 wfDebug( "Unknown error sending mail\n" );
379 return Status::newFatal( 'php-mail-error-unknown' );
380 } else {
381 return Status::newGood();
382 }
383 }
384 }
385
386 /**
387 * Set the mail error message in self::$mErrorString
388 *
389 * @param $code Integer: error number
390 * @param string $string error message
391 */
392 static function errorHandler( $code, $string ) {
393 self::$mErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
394 }
395
396 /**
397 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
398 * @param $phrase string
399 * @return string
400 */
401 public static function rfc822Phrase( $phrase ) {
402 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
403 return '"' . $phrase . '"';
404 }
405
406 /**
407 * Converts a string into quoted-printable format
408 * @since 1.17
409 *
410 * From PHP5.3 there is a built in function quoted_printable_encode()
411 * This method does not duplicate that.
412 * This method is doing Q encoding inside encoded-words as defined by RFC 2047
413 * This is for email headers.
414 * The built in quoted_printable_encode() is for email bodies
415 * @return string
416 */
417 public static function quotedPrintable( $string, $charset = '' ) {
418 # Probably incomplete; see RFC 2045
419 if ( empty( $charset ) ) {
420 $charset = 'UTF-8';
421 }
422 $charset = strtoupper( $charset );
423 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
424
425 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
426 $replace = $illegal . '\t ?_';
427 if ( !preg_match( "/[$illegal]/", $string ) ) {
428 return $string;
429 }
430 $out = "=?$charset?Q?";
431 $out .= preg_replace_callback( "/([$replace])/",
432 array( __CLASS__, 'quotedPrintableCallback' ), $string );
433 $out .= '?=';
434 return $out;
435 }
436
437 protected static function quotedPrintableCallback( $matches ) {
438 return sprintf( "=%02X", ord( $matches[1] ) );
439 }
440 }
441
442 /**
443 * This module processes the email notifications when the current page is
444 * changed. It looks up the table watchlist to find out which users are watching
445 * that page.
446 *
447 * The current implementation sends independent emails to each watching user for
448 * the following reason:
449 *
450 * - Each watching user will be notified about the page edit time expressed in
451 * his/her local time (UTC is shown additionally). To achieve this, we need to
452 * find the individual timeoffset of each watching user from the preferences..
453 *
454 * Suggested improvement to slack down the number of sent emails: We could think
455 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
456 * same timeoffset in their preferences.
457 *
458 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
459 *
460 *
461 */
462 class EmailNotification {
463 protected $subject, $body, $replyto, $from;
464 protected $timestamp, $summary, $minorEdit, $oldid, $composed_common, $pageStatus;
465 protected $mailTargets = array();
466
467 /**
468 * @var Title
469 */
470 protected $title;
471
472 /**
473 * @var User
474 */
475 protected $editor;
476
477 /**
478 * Send emails corresponding to the user $editor editing the page $title.
479 * Also updates wl_notificationtimestamp.
480 *
481 * May be deferred via the job queue.
482 *
483 * @param $editor User object
484 * @param $title Title object
485 * @param $timestamp
486 * @param $summary
487 * @param $minorEdit
488 * @param $oldid (default: false)
489 * @param $pageStatus (default: 'changed')
490 */
491 public function notifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid = false, $pageStatus = 'changed' ) {
492 global $wgEnotifUseJobQ, $wgEnotifWatchlist, $wgShowUpdatedMarker, $wgEnotifMinorEdits,
493 $wgUsersNotifiedOnAllChanges, $wgEnotifUserTalk;
494
495 if ( $title->getNamespace() < 0 ) {
496 return;
497 }
498
499 // Build a list of users to notify
500 $watchers = array();
501 if ( $wgEnotifWatchlist || $wgShowUpdatedMarker ) {
502 $dbw = wfGetDB( DB_MASTER );
503 $res = $dbw->select( array( 'watchlist' ),
504 array( 'wl_user' ),
505 array(
506 'wl_user != ' . intval( $editor->getID() ),
507 'wl_namespace' => $title->getNamespace(),
508 'wl_title' => $title->getDBkey(),
509 'wl_notificationtimestamp IS NULL',
510 ), __METHOD__
511 );
512 foreach ( $res as $row ) {
513 $watchers[] = intval( $row->wl_user );
514 }
515 if ( $watchers ) {
516 // Update wl_notificationtimestamp for all watching users except the editor
517 $fname = __METHOD__;
518 $dbw->onTransactionIdle(
519 function() use ( $dbw, $timestamp, $watchers, $title, $fname ) {
520 $dbw->begin( $fname );
521 $dbw->update( 'watchlist',
522 array( /* SET */
523 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
524 ), array( /* WHERE */
525 'wl_user' => $watchers,
526 'wl_namespace' => $title->getNamespace(),
527 'wl_title' => $title->getDBkey(),
528 ), $fname
529 );
530 $dbw->commit( $fname );
531 }
532 );
533 }
534 }
535
536 $sendEmail = true;
537 // If nobody is watching the page, and there are no users notified on all changes
538 // don't bother creating a job/trying to send emails
539 // $watchers deals with $wgEnotifWatchlist
540 if ( !count( $watchers ) && !count( $wgUsersNotifiedOnAllChanges ) ) {
541 $sendEmail = false;
542 // Only send notification for non minor edits, unless $wgEnotifMinorEdits
543 if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
544 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
545 if ( $wgEnotifUserTalk && $isUserTalkPage && $this->canSendUserTalkEmail( $editor, $title, $minorEdit ) ) {
546 $sendEmail = true;
547 }
548 }
549 }
550
551 if ( !$sendEmail ) {
552 return;
553 }
554 if ( $wgEnotifUseJobQ ) {
555 $params = array(
556 'editor' => $editor->getName(),
557 'editorID' => $editor->getID(),
558 'timestamp' => $timestamp,
559 'summary' => $summary,
560 'minorEdit' => $minorEdit,
561 'oldid' => $oldid,
562 'watchers' => $watchers,
563 'pageStatus' => $pageStatus
564 );
565 $job = new EnotifNotifyJob( $title, $params );
566 JobQueueGroup::singleton()->push( $job );
567 } else {
568 $this->actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers, $pageStatus );
569 }
570 }
571
572 /**
573 * Immediate version of notifyOnPageChange().
574 *
575 * Send emails corresponding to the user $editor editing the page $title.
576 * Also updates wl_notificationtimestamp.
577 *
578 * @param $editor User object
579 * @param $title Title object
580 * @param string $timestamp Edit timestamp
581 * @param string $summary Edit summary
582 * @param $minorEdit bool
583 * @param int $oldid Revision ID
584 * @param array $watchers of user IDs
585 * @param string $pageStatus
586 * @throws MWException
587 */
588 public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit,
589 $oldid, $watchers, $pageStatus = 'changed' ) {
590 # we use $wgPasswordSender as sender's address
591 global $wgEnotifWatchlist;
592 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
593
594 wfProfileIn( __METHOD__ );
595
596 # The following code is only run, if several conditions are met:
597 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
598 # 2. minor edits (changes) are only regarded if the global flag indicates so
599
600 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
601
602 $this->title = $title;
603 $this->timestamp = $timestamp;
604 $this->summary = $summary;
605 $this->minorEdit = $minorEdit;
606 $this->oldid = $oldid;
607 $this->editor = $editor;
608 $this->composed_common = false;
609 $this->pageStatus = $pageStatus;
610
611 $formattedPageStatus = array( 'deleted', 'created', 'moved', 'restored', 'changed' );
612
613 wfRunHooks( 'UpdateUserMailerFormattedPageStatus', array( &$formattedPageStatus ) );
614 if ( !in_array( $this->pageStatus, $formattedPageStatus ) ) {
615 wfProfileOut( __METHOD__ );
616 throw new MWException( 'Not a valid page status!' );
617 }
618
619 $userTalkId = false;
620
621 if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
622
623 if ( $wgEnotifUserTalk && $isUserTalkPage && $this->canSendUserTalkEmail( $editor, $title, $minorEdit ) ) {
624 $targetUser = User::newFromName( $title->getText() );
625 $this->compose( $targetUser );
626 $userTalkId = $targetUser->getId();
627 }
628
629 if ( $wgEnotifWatchlist ) {
630 // Send updates to watchers other than the current editor
631 $userArray = UserArray::newFromIDs( $watchers );
632 foreach ( $userArray as $watchingUser ) {
633 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
634 ( !$minorEdit || $watchingUser->getOption( 'enotifminoredits' ) ) &&
635 $watchingUser->isEmailConfirmed() &&
636 $watchingUser->getID() != $userTalkId )
637 {
638 $this->compose( $watchingUser );
639 }
640 }
641 }
642 }
643
644 global $wgUsersNotifiedOnAllChanges;
645 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
646 if ( $editor->getName() == $name ) {
647 // No point notifying the user that actually made the change!
648 continue;
649 }
650 $user = User::newFromName( $name );
651 $this->compose( $user );
652 }
653
654 $this->sendMails();
655 wfProfileOut( __METHOD__ );
656 }
657
658 /**
659 * @param $editor User
660 * @param $title Title bool
661 * @param $minorEdit
662 * @return bool
663 */
664 private function canSendUserTalkEmail( $editor, $title, $minorEdit ) {
665 global $wgEnotifUserTalk;
666 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
667
668 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
669 $targetUser = User::newFromName( $title->getText() );
670
671 if ( !$targetUser || $targetUser->isAnon() ) {
672 wfDebug( __METHOD__ . ": user talk page edited, but user does not exist\n" );
673 } elseif ( $targetUser->getId() == $editor->getId() ) {
674 wfDebug( __METHOD__ . ": user edited their own talk page, no notification sent\n" );
675 } elseif ( $targetUser->getOption( 'enotifusertalkpages' ) &&
676 ( !$minorEdit || $targetUser->getOption( 'enotifminoredits' ) ) )
677 {
678 if ( !$targetUser->isEmailConfirmed() ) {
679 wfDebug( __METHOD__ . ": talk page owner doesn't have validated email\n" );
680 } elseif ( !wfRunHooks( 'AbortTalkPageEmailNotification', array( $targetUser, $title ) ) ) {
681 wfDebug( __METHOD__ . ": talk page update notification is aborted for this user\n" );
682 } else {
683 wfDebug( __METHOD__ . ": sending talk page update notification\n" );
684 return true;
685 }
686 } else {
687 wfDebug( __METHOD__ . ": talk page owner doesn't want notifications\n" );
688 }
689 }
690 return false;
691 }
692
693 /**
694 * Generate the generic "this page has been changed" e-mail text.
695 */
696 private function composeCommonMailtext() {
697 global $wgPasswordSender, $wgPasswordSenderName, $wgNoReplyAddress;
698 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
699 global $wgEnotifImpersonal, $wgEnotifUseRealName;
700
701 $this->composed_common = true;
702
703 # You as the WikiAdmin and Sysops can make use of plenty of
704 # named variables when composing your notification emails while
705 # simply editing the Meta pages
706
707 $keys = array();
708 $postTransformKeys = array();
709 $pageTitleUrl = $this->title->getCanonicalURL();
710 $pageTitle = $this->title->getPrefixedText();
711
712 if ( $this->oldid ) {
713 // Always show a link to the diff which triggered the mail. See bug 32210.
714 $keys['$NEWPAGE'] = "\n\n" . wfMessage( 'enotif_lastdiff',
715 $this->title->getCanonicalURL( array( 'diff' => 'next', 'oldid' => $this->oldid ) ) )
716 ->inContentLanguage()->text();
717
718 if ( !$wgEnotifImpersonal ) {
719 // For personal mail, also show a link to the diff of all changes
720 // since last visited.
721 $keys['$NEWPAGE'] .= "\n\n" . wfMessage( 'enotif_lastvisited',
722 $this->title->getCanonicalURL( array( 'diff' => '0', 'oldid' => $this->oldid ) ) )
723 ->inContentLanguage()->text();
724 }
725 $keys['$OLDID'] = $this->oldid;
726 // @deprecated Remove in MediaWiki 1.23.
727 $keys['$CHANGEDORCREATED'] = wfMessage( 'changed' )->inContentLanguage()->text();
728 } else {
729 # clear $OLDID placeholder in the message template
730 $keys['$OLDID'] = '';
731 $keys['$NEWPAGE'] = '';
732 // @deprecated Remove in MediaWiki 1.23.
733 $keys['$CHANGEDORCREATED'] = wfMessage( 'created' )->inContentLanguage()->text();
734 }
735
736 $keys['$PAGETITLE'] = $this->title->getPrefixedText();
737 $keys['$PAGETITLE_URL'] = $this->title->getCanonicalURL();
738 $keys['$PAGEMINOREDIT'] = $this->minorEdit ?
739 wfMessage( 'minoredit' )->inContentLanguage()->text() : '';
740 $keys['$UNWATCHURL'] = $this->title->getCanonicalURL( 'action=unwatch' );
741
742 if ( $this->editor->isAnon() ) {
743 # real anon (user:xxx.xxx.xxx.xxx)
744 $keys['$PAGEEDITOR'] = wfMessage( 'enotif_anon_editor', $this->editor->getName() )
745 ->inContentLanguage()->text();
746 $keys['$PAGEEDITOR_EMAIL'] = wfMessage( 'noemailtitle' )->inContentLanguage()->text();
747
748 } else {
749 $keys['$PAGEEDITOR'] = $wgEnotifUseRealName ? $this->editor->getRealName() : $this->editor->getName();
750 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $this->editor->getName() );
751 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getCanonicalURL();
752 }
753
754 $keys['$PAGEEDITOR_WIKI'] = $this->editor->getUserPage()->getCanonicalURL();
755
756 # Replace this after transforming the message, bug 35019
757 $postTransformKeys['$PAGESUMMARY'] = $this->summary == '' ? ' - ' : $this->summary;
758
759 // Now build message's subject and body
760
761 // Messages:
762 // enotif_subject_deleted, enotif_subject_created, enotif_subject_moved,
763 // enotif_subject_restored, enotif_subject_changed
764 $this->subject = wfMessage( 'enotif_subject_' . $this->pageStatus )->inContentLanguage()
765 ->params( $pageTitle, $keys['$PAGEEDITOR'] )->text();
766
767 // Messages:
768 // enotif_body_intro_deleted, enotif_body_intro_created, enotif_body_intro_moved,
769 // enotif_body_intro_restored, enotif_body_intro_changed
770 $keys['$PAGEINTRO'] = wfMessage( 'enotif_body_intro_' . $this->pageStatus )
771 ->inContentLanguage()->params( $pageTitle, $keys['$PAGEEDITOR'], $pageTitleUrl )
772 ->text();
773
774 $body = wfMessage( 'enotif_body' )->inContentLanguage()->plain();
775 $body = strtr( $body, $keys );
776 $body = MessageCache::singleton()->transform( $body, false, null, $this->title );
777 $this->body = wordwrap( strtr( $body, $postTransformKeys ), 72 );
778
779 # Reveal the page editor's address as REPLY-TO address only if
780 # the user has not opted-out and the option is enabled at the
781 # global configuration level.
782 $adminAddress = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
783 if ( $wgEnotifRevealEditorAddress
784 && ( $this->editor->getEmail() != '' )
785 && $this->editor->getOption( 'enotifrevealaddr' ) )
786 {
787 $editorAddress = new MailAddress( $this->editor );
788 if ( $wgEnotifFromEditor ) {
789 $this->from = $editorAddress;
790 } else {
791 $this->from = $adminAddress;
792 $this->replyto = $editorAddress;
793 }
794 } else {
795 $this->from = $adminAddress;
796 $this->replyto = new MailAddress( $wgNoReplyAddress );
797 }
798 }
799
800 /**
801 * Compose a mail to a given user and either queue it for sending, or send it now,
802 * depending on settings.
803 *
804 * Call sendMails() to send any mails that were queued.
805 * @param $user User
806 */
807 function compose( $user ) {
808 global $wgEnotifImpersonal;
809
810 if ( !$this->composed_common ) {
811 $this->composeCommonMailtext();
812 }
813
814 if ( $wgEnotifImpersonal ) {
815 $this->mailTargets[] = new MailAddress( $user );
816 } else {
817 $this->sendPersonalised( $user );
818 }
819 }
820
821 /**
822 * Send any queued mails
823 */
824 function sendMails() {
825 global $wgEnotifImpersonal;
826 if ( $wgEnotifImpersonal ) {
827 $this->sendImpersonal( $this->mailTargets );
828 }
829 }
830
831 /**
832 * Does the per-user customizations to a notification e-mail (name,
833 * timestamp in proper timezone, etc) and sends it out.
834 * Returns true if the mail was sent successfully.
835 *
836 * @param $watchingUser User object
837 * @return Boolean
838 * @private
839 */
840 function sendPersonalised( $watchingUser ) {
841 global $wgContLang, $wgEnotifUseRealName;
842 // From the PHP manual:
843 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
844 // The mail command will not parse this properly while talking with the MTA.
845 $to = new MailAddress( $watchingUser );
846
847 # $PAGEEDITDATE is the time and date of the page change
848 # expressed in terms of individual local time of the notification
849 # recipient, i.e. watching user
850 $body = str_replace(
851 array( '$WATCHINGUSERNAME',
852 '$PAGEEDITDATE',
853 '$PAGEEDITTIME' ),
854 array( $wgEnotifUseRealName ? $watchingUser->getRealName() : $watchingUser->getName(),
855 $wgContLang->userDate( $this->timestamp, $watchingUser ),
856 $wgContLang->userTime( $this->timestamp, $watchingUser ) ),
857 $this->body );
858
859 return UserMailer::send( $to, $this->from, $this->subject, $body, $this->replyto );
860 }
861
862 /**
863 * Same as sendPersonalised but does impersonal mail suitable for bulk
864 * mailing. Takes an array of MailAddress objects.
865 * @param $addresses array
866 * @return Status|null
867 */
868 function sendImpersonal( $addresses ) {
869 global $wgContLang;
870
871 if ( empty( $addresses ) ) {
872 return null;
873 }
874
875 $body = str_replace(
876 array( '$WATCHINGUSERNAME',
877 '$PAGEEDITDATE',
878 '$PAGEEDITTIME' ),
879 array( wfMessage( 'enotif_impersonal_salutation' )->inContentLanguage()->text(),
880 $wgContLang->date( $this->timestamp, false, false ),
881 $wgContLang->time( $this->timestamp, false, false ) ),
882 $this->body );
883
884 return UserMailer::send( $addresses, $this->from, $this->subject, $body, $this->replyto );
885 }
886
887 } # end of class EmailNotification