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