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