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