Merge "Include action in permission error messages"
[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 * @param string $string
452 * @param string $charset
453 * @return string
454 */
455 public static function quotedPrintable( $string, $charset = '' ) {
456 # Probably incomplete; see RFC 2045
457 if ( empty( $charset ) ) {
458 $charset = 'UTF-8';
459 }
460 $charset = strtoupper( $charset );
461 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
462
463 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
464 $replace = $illegal . '\t ?_';
465 if ( !preg_match( "/[$illegal]/", $string ) ) {
466 return $string;
467 }
468 $out = "=?$charset?Q?";
469 $out .= preg_replace_callback( "/([$replace])/",
470 array( __CLASS__, 'quotedPrintableCallback' ), $string );
471 $out .= '?=';
472 return $out;
473 }
474
475 protected static function quotedPrintableCallback( $matches ) {
476 return sprintf( "=%02X", ord( $matches[1] ) );
477 }
478 }
479
480 /**
481 * This module processes the email notifications when the current page is
482 * changed. It looks up the table watchlist to find out which users are watching
483 * that page.
484 *
485 * The current implementation sends independent emails to each watching user for
486 * the following reason:
487 *
488 * - Each watching user will be notified about the page edit time expressed in
489 * his/her local time (UTC is shown additionally). To achieve this, we need to
490 * find the individual timeoffset of each watching user from the preferences..
491 *
492 * Suggested improvement to slack down the number of sent emails: We could think
493 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
494 * same timeoffset in their preferences.
495 *
496 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
497 *
498 *
499 */
500 class EmailNotification {
501 protected $subject, $body, $replyto, $from;
502 protected $timestamp, $summary, $minorEdit, $oldid, $composed_common, $pageStatus;
503 protected $mailTargets = array();
504
505 /**
506 * @var Title
507 */
508 protected $title;
509
510 /**
511 * @var User
512 */
513 protected $editor;
514
515 /**
516 * Send emails corresponding to the user $editor editing the page $title.
517 * Also updates wl_notificationtimestamp.
518 *
519 * May be deferred via the job queue.
520 *
521 * @param User $editor
522 * @param Title $title
523 * @param string $timestamp
524 * @param string $summary
525 * @param bool $minorEdit
526 * @param bool $oldid (default: false)
527 * @param string $pageStatus (default: 'changed')
528 */
529 public function notifyOnPageChange( $editor, $title, $timestamp, $summary,
530 $minorEdit, $oldid = false, $pageStatus = 'changed'
531 ) {
532 global $wgEnotifUseJobQ, $wgEnotifWatchlist, $wgShowUpdatedMarker, $wgEnotifMinorEdits,
533 $wgUsersNotifiedOnAllChanges, $wgEnotifUserTalk;
534
535 if ( $title->getNamespace() < 0 ) {
536 return;
537 }
538
539 // Build a list of users to notify
540 $watchers = array();
541 if ( $wgEnotifWatchlist || $wgShowUpdatedMarker ) {
542 $dbw = wfGetDB( DB_MASTER );
543 $res = $dbw->select( array( 'watchlist' ),
544 array( 'wl_user' ),
545 array(
546 'wl_user != ' . intval( $editor->getID() ),
547 'wl_namespace' => $title->getNamespace(),
548 'wl_title' => $title->getDBkey(),
549 'wl_notificationtimestamp IS NULL',
550 ), __METHOD__
551 );
552 foreach ( $res as $row ) {
553 $watchers[] = intval( $row->wl_user );
554 }
555 if ( $watchers ) {
556 // Update wl_notificationtimestamp for all watching users except the editor
557 $fname = __METHOD__;
558 $dbw->onTransactionIdle(
559 function () use ( $dbw, $timestamp, $watchers, $title, $fname ) {
560 $dbw->update( 'watchlist',
561 array( /* SET */
562 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
563 ), array( /* WHERE */
564 'wl_user' => $watchers,
565 'wl_namespace' => $title->getNamespace(),
566 'wl_title' => $title->getDBkey(),
567 ), $fname
568 );
569 }
570 );
571 }
572 }
573
574 $sendEmail = true;
575 // If nobody is watching the page, and there are no users notified on all changes
576 // don't bother creating a job/trying to send emails
577 // $watchers deals with $wgEnotifWatchlist
578 if ( !count( $watchers ) && !count( $wgUsersNotifiedOnAllChanges ) ) {
579 $sendEmail = false;
580 // Only send notification for non minor edits, unless $wgEnotifMinorEdits
581 if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
582 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
583 if ( $wgEnotifUserTalk
584 && $isUserTalkPage
585 && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
586 ) {
587 $sendEmail = true;
588 }
589 }
590 }
591
592 if ( !$sendEmail ) {
593 return;
594 }
595
596 if ( $wgEnotifUseJobQ ) {
597 $params = array(
598 'editor' => $editor->getName(),
599 'editorID' => $editor->getID(),
600 'timestamp' => $timestamp,
601 'summary' => $summary,
602 'minorEdit' => $minorEdit,
603 'oldid' => $oldid,
604 'watchers' => $watchers,
605 'pageStatus' => $pageStatus
606 );
607 $job = new EnotifNotifyJob( $title, $params );
608 JobQueueGroup::singleton()->push( $job );
609 } else {
610 $this->actuallyNotifyOnPageChange(
611 $editor,
612 $title,
613 $timestamp,
614 $summary,
615 $minorEdit,
616 $oldid,
617 $watchers,
618 $pageStatus
619 );
620 }
621 }
622
623 /**
624 * Immediate version of notifyOnPageChange().
625 *
626 * Send emails corresponding to the user $editor editing the page $title.
627 * Also updates wl_notificationtimestamp.
628 *
629 * @param User $editor
630 * @param Title $title
631 * @param string $timestamp Edit timestamp
632 * @param string $summary Edit summary
633 * @param bool $minorEdit
634 * @param int $oldid Revision ID
635 * @param array $watchers Array of user IDs
636 * @param string $pageStatus
637 * @throws MWException
638 */
639 public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit,
640 $oldid, $watchers, $pageStatus = 'changed' ) {
641 # we use $wgPasswordSender as sender's address
642 global $wgEnotifWatchlist;
643 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
644
645 wfProfileIn( __METHOD__ );
646
647 # The following code is only run, if several conditions are met:
648 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
649 # 2. minor edits (changes) are only regarded if the global flag indicates so
650
651 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
652
653 $this->title = $title;
654 $this->timestamp = $timestamp;
655 $this->summary = $summary;
656 $this->minorEdit = $minorEdit;
657 $this->oldid = $oldid;
658 $this->editor = $editor;
659 $this->composed_common = false;
660 $this->pageStatus = $pageStatus;
661
662 $formattedPageStatus = array( 'deleted', 'created', 'moved', 'restored', 'changed' );
663
664 wfRunHooks( 'UpdateUserMailerFormattedPageStatus', array( &$formattedPageStatus ) );
665 if ( !in_array( $this->pageStatus, $formattedPageStatus ) ) {
666 wfProfileOut( __METHOD__ );
667 throw new MWException( 'Not a valid page status!' );
668 }
669
670 $userTalkId = false;
671
672 if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
673 if ( $wgEnotifUserTalk
674 && $isUserTalkPage
675 && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
676 ) {
677 $targetUser = User::newFromName( $title->getText() );
678 $this->compose( $targetUser );
679 $userTalkId = $targetUser->getId();
680 }
681
682 if ( $wgEnotifWatchlist ) {
683 // Send updates to watchers other than the current editor
684 $userArray = UserArray::newFromIDs( $watchers );
685 foreach ( $userArray as $watchingUser ) {
686 if ( $watchingUser->getOption( 'enotifwatchlistpages' )
687 && ( !$minorEdit || $watchingUser->getOption( 'enotifminoredits' ) )
688 && $watchingUser->isEmailConfirmed()
689 && $watchingUser->getID() != $userTalkId
690 ) {
691 if ( wfRunHooks( 'SendWatchlistEmailNotification', array( $watchingUser, $title, $this ) ) ) {
692 $this->compose( $watchingUser );
693 }
694 }
695 }
696 }
697 }
698
699 global $wgUsersNotifiedOnAllChanges;
700 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
701 if ( $editor->getName() == $name ) {
702 // No point notifying the user that actually made the change!
703 continue;
704 }
705 $user = User::newFromName( $name );
706 $this->compose( $user );
707 }
708
709 $this->sendMails();
710 wfProfileOut( __METHOD__ );
711 }
712
713 /**
714 * @param User $editor
715 * @param Title $title
716 * @param bool $minorEdit
717 * @return bool
718 */
719 private function canSendUserTalkEmail( $editor, $title, $minorEdit ) {
720 global $wgEnotifUserTalk;
721 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
722
723 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
724 $targetUser = User::newFromName( $title->getText() );
725
726 if ( !$targetUser || $targetUser->isAnon() ) {
727 wfDebug( __METHOD__ . ": user talk page edited, but user does not exist\n" );
728 } elseif ( $targetUser->getId() == $editor->getId() ) {
729 wfDebug( __METHOD__ . ": user edited their own talk page, no notification sent\n" );
730 } elseif ( $targetUser->getOption( 'enotifusertalkpages' )
731 && ( !$minorEdit || $targetUser->getOption( 'enotifminoredits' ) )
732 ) {
733 if ( !$targetUser->isEmailConfirmed() ) {
734 wfDebug( __METHOD__ . ": talk page owner doesn't have validated email\n" );
735 } elseif ( !wfRunHooks( 'AbortTalkPageEmailNotification', array( $targetUser, $title ) ) ) {
736 wfDebug( __METHOD__ . ": talk page update notification is aborted for this user\n" );
737 } else {
738 wfDebug( __METHOD__ . ": sending talk page update notification\n" );
739 return true;
740 }
741 } else {
742 wfDebug( __METHOD__ . ": talk page owner doesn't want notifications\n" );
743 }
744 }
745 return false;
746 }
747
748 /**
749 * Generate the generic "this page has been changed" e-mail text.
750 */
751 private function composeCommonMailtext() {
752 global $wgPasswordSender, $wgNoReplyAddress;
753 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
754 global $wgEnotifImpersonal, $wgEnotifUseRealName;
755
756 $this->composed_common = true;
757
758 # You as the WikiAdmin and Sysops can make use of plenty of
759 # named variables when composing your notification emails while
760 # simply editing the Meta pages
761
762 $keys = array();
763 $postTransformKeys = array();
764 $pageTitleUrl = $this->title->getCanonicalURL();
765 $pageTitle = $this->title->getPrefixedText();
766
767 if ( $this->oldid ) {
768 // Always show a link to the diff which triggered the mail. See bug 32210.
769 $keys['$NEWPAGE'] = "\n\n" . wfMessage( 'enotif_lastdiff',
770 $this->title->getCanonicalURL( array( 'diff' => 'next', 'oldid' => $this->oldid ) ) )
771 ->inContentLanguage()->text();
772
773 if ( !$wgEnotifImpersonal ) {
774 // For personal mail, also show a link to the diff of all changes
775 // since last visited.
776 $keys['$NEWPAGE'] .= "\n\n" . wfMessage( 'enotif_lastvisited',
777 $this->title->getCanonicalURL( array( 'diff' => '0', 'oldid' => $this->oldid ) ) )
778 ->inContentLanguage()->text();
779 }
780 $keys['$OLDID'] = $this->oldid;
781 // Deprecated since MediaWiki 1.21, not used by default. Kept for backwards-compatibility.
782 $keys['$CHANGEDORCREATED'] = wfMessage( 'changed' )->inContentLanguage()->text();
783 } else {
784 # clear $OLDID placeholder in the message template
785 $keys['$OLDID'] = '';
786 $keys['$NEWPAGE'] = '';
787 // Deprecated since MediaWiki 1.21, not used by default. Kept for backwards-compatibility.
788 $keys['$CHANGEDORCREATED'] = wfMessage( 'created' )->inContentLanguage()->text();
789 }
790
791 $keys['$PAGETITLE'] = $this->title->getPrefixedText();
792 $keys['$PAGETITLE_URL'] = $this->title->getCanonicalURL();
793 $keys['$PAGEMINOREDIT'] = $this->minorEdit ?
794 wfMessage( 'minoredit' )->inContentLanguage()->text() : '';
795 $keys['$UNWATCHURL'] = $this->title->getCanonicalURL( 'action=unwatch' );
796
797 if ( $this->editor->isAnon() ) {
798 # real anon (user:xxx.xxx.xxx.xxx)
799 $keys['$PAGEEDITOR'] = wfMessage( 'enotif_anon_editor', $this->editor->getName() )
800 ->inContentLanguage()->text();
801 $keys['$PAGEEDITOR_EMAIL'] = wfMessage( 'noemailtitle' )->inContentLanguage()->text();
802
803 } else {
804 $keys['$PAGEEDITOR'] = $wgEnotifUseRealName && $this->editor->getRealName() !== ''
805 ? $this->editor->getRealName() : $this->editor->getName();
806 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $this->editor->getName() );
807 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getCanonicalURL();
808 }
809
810 $keys['$PAGEEDITOR_WIKI'] = $this->editor->getUserPage()->getCanonicalURL();
811 $keys['$HELPPAGE'] = wfExpandUrl(
812 Skin::makeInternalOrExternalUrl( wfMessage( 'helppage' )->inContentLanguage()->text() )
813 );
814
815 # Replace this after transforming the message, bug 35019
816 $postTransformKeys['$PAGESUMMARY'] = $this->summary == '' ? ' - ' : $this->summary;
817
818 // Now build message's subject and body
819
820 // Messages:
821 // enotif_subject_deleted, enotif_subject_created, enotif_subject_moved,
822 // enotif_subject_restored, enotif_subject_changed
823 $this->subject = wfMessage( 'enotif_subject_' . $this->pageStatus )->inContentLanguage()
824 ->params( $pageTitle, $keys['$PAGEEDITOR'] )->text();
825
826 // Messages:
827 // enotif_body_intro_deleted, enotif_body_intro_created, enotif_body_intro_moved,
828 // enotif_body_intro_restored, enotif_body_intro_changed
829 $keys['$PAGEINTRO'] = wfMessage( 'enotif_body_intro_' . $this->pageStatus )
830 ->inContentLanguage()->params( $pageTitle, $keys['$PAGEEDITOR'], $pageTitleUrl )
831 ->text();
832
833 $body = wfMessage( 'enotif_body' )->inContentLanguage()->plain();
834 $body = strtr( $body, $keys );
835 $body = MessageCache::singleton()->transform( $body, false, null, $this->title );
836 $this->body = wordwrap( strtr( $body, $postTransformKeys ), 72 );
837
838 # Reveal the page editor's address as REPLY-TO address only if
839 # the user has not opted-out and the option is enabled at the
840 # global configuration level.
841 $adminAddress = new MailAddress( $wgPasswordSender,
842 wfMessage( 'emailsender' )->inContentLanguage()->text() );
843 if ( $wgEnotifRevealEditorAddress
844 && ( $this->editor->getEmail() != '' )
845 && $this->editor->getOption( 'enotifrevealaddr' )
846 ) {
847 $editorAddress = new MailAddress( $this->editor );
848 if ( $wgEnotifFromEditor ) {
849 $this->from = $editorAddress;
850 } else {
851 $this->from = $adminAddress;
852 $this->replyto = $editorAddress;
853 }
854 } else {
855 $this->from = $adminAddress;
856 $this->replyto = new MailAddress( $wgNoReplyAddress );
857 }
858 }
859
860 /**
861 * Compose a mail to a given user and either queue it for sending, or send it now,
862 * depending on settings.
863 *
864 * Call sendMails() to send any mails that were queued.
865 * @param User $user
866 */
867 function compose( $user ) {
868 global $wgEnotifImpersonal;
869
870 if ( !$this->composed_common ) {
871 $this->composeCommonMailtext();
872 }
873
874 if ( $wgEnotifImpersonal ) {
875 $this->mailTargets[] = new MailAddress( $user );
876 } else {
877 $this->sendPersonalised( $user );
878 }
879 }
880
881 /**
882 * Send any queued mails
883 */
884 function sendMails() {
885 global $wgEnotifImpersonal;
886 if ( $wgEnotifImpersonal ) {
887 $this->sendImpersonal( $this->mailTargets );
888 }
889 }
890
891 /**
892 * Does the per-user customizations to a notification e-mail (name,
893 * timestamp in proper timezone, etc) and sends it out.
894 * Returns true if the mail was sent successfully.
895 *
896 * @param User $watchingUser
897 * @return bool
898 * @private
899 */
900 function sendPersonalised( $watchingUser ) {
901 global $wgContLang, $wgEnotifUseRealName;
902 // From the PHP manual:
903 // Note: The to parameter cannot be an address in the form of
904 // "Something <someone@example.com>". The mail command will not parse
905 // this properly while talking with the MTA.
906 $to = new MailAddress( $watchingUser );
907
908 # $PAGEEDITDATE is the time and date of the page change
909 # expressed in terms of individual local time of the notification
910 # recipient, i.e. watching user
911 $body = str_replace(
912 array( '$WATCHINGUSERNAME',
913 '$PAGEEDITDATE',
914 '$PAGEEDITTIME' ),
915 array( $wgEnotifUseRealName && $watchingUser->getRealName() !== ''
916 ? $watchingUser->getRealName() : $watchingUser->getName(),
917 $wgContLang->userDate( $this->timestamp, $watchingUser ),
918 $wgContLang->userTime( $this->timestamp, $watchingUser ) ),
919 $this->body );
920
921 return UserMailer::send( $to, $this->from, $this->subject, $body, $this->replyto );
922 }
923
924 /**
925 * Same as sendPersonalised but does impersonal mail suitable for bulk
926 * mailing. Takes an array of MailAddress objects.
927 * @param MailAddress[] $addresses
928 * @return Status|null
929 */
930 function sendImpersonal( $addresses ) {
931 global $wgContLang;
932
933 if ( empty( $addresses ) ) {
934 return null;
935 }
936
937 $body = str_replace(
938 array( '$WATCHINGUSERNAME',
939 '$PAGEEDITDATE',
940 '$PAGEEDITTIME' ),
941 array( wfMessage( 'enotif_impersonal_salutation' )->inContentLanguage()->text(),
942 $wgContLang->date( $this->timestamp, false, false ),
943 $wgContLang->time( $this->timestamp, false, false ) ),
944 $this->body );
945
946 return UserMailer::send( $addresses, $this->from, $this->subject, $body, $this->replyto );
947 }
948
949 } # end of class EmailNotification