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