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