3 * Implements Special:Emailuser
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.
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.
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
21 * @ingroup SpecialPage
23 use MediaWiki\MediaWikiServices
;
24 use MediaWiki\Preferences\MultiUsernameFilter
;
27 * A special page that allows users to send e-mails to other users
29 * @ingroup SpecialPage
31 class SpecialEmailUser
extends UnlistedSpecialPage
{
35 * @var User|string $mTargetObj
37 protected $mTargetObj;
39 public function __construct() {
40 parent
::__construct( 'Emailuser' );
43 public function doesWrites() {
47 public function getDescription() {
48 $target = self
::getTarget( $this->mTarget
, $this->getUser() );
49 if ( !$target instanceof User
) {
50 return $this->msg( 'emailuser-title-notarget' )->text();
53 return $this->msg( 'emailuser-title-target', $target->getName() )->text();
56 protected function getFormFields() {
57 $linkRenderer = $this->getLinkRenderer();
62 'default' => $linkRenderer->makeLink(
63 $this->getUser()->getUserPage(),
64 $this->getUser()->getName()
66 'label-message' => 'emailfrom',
67 'id' => 'mw-emailuser-sender',
72 'default' => $linkRenderer->makeLink(
73 $this->mTargetObj
->getUserPage(),
74 $this->mTargetObj
->getName()
76 'label-message' => 'emailto',
77 'id' => 'mw-emailuser-recipient',
81 'default' => $this->mTargetObj
->getName(),
85 'default' => $this->msg( 'defemailsubject',
86 $this->getUser()->getName() )->inContentLanguage()->text(),
87 'label-message' => 'emailsubject',
96 'label-message' => 'emailmessage',
101 'label-message' => 'emailccme',
102 'default' => $this->getUser()->getBoolOption( 'ccmeonemails' ),
107 public function execute( $par ) {
108 $out = $this->getOutput();
109 $out->addModuleStyles( 'mediawiki.special' );
111 $this->mTarget
= is_null( $par )
112 ?
$this->getRequest()->getVal( 'wpTarget', $this->getRequest()->getVal( 'target', '' ) )
115 // This needs to be below assignment of $this->mTarget because
116 // getDescription() needs it to determine the correct page title.
118 $this->outputHeader();
120 // error out if sending user cannot do this
121 $error = self
::getPermissionsError(
123 $this->getRequest()->getVal( 'wpEditToken' ),
132 throw new PermissionsError( 'sendemail' );
133 case 'blockedemailuser':
134 throw $this->getBlockedEmailError();
135 case 'actionthrottledtext':
136 throw new ThrottledError
;
138 case 'usermaildisabled':
139 throw new ErrorPageError( $error, "{$error}text" );
142 list( $title, $msg, $params ) = $error;
143 throw new ErrorPageError( $title, $msg, $params );
145 // Got a valid target user name? Else ask for one.
146 $ret = self
::getTarget( $this->mTarget
, $this->getUser() );
147 if ( !$ret instanceof User
) {
148 if ( $this->mTarget
!= '' ) {
149 // Messages used here: notargettext, noemailtext, nowikiemailtext
150 $ret = ( $ret == 'notarget' ) ?
'emailnotarget' : ( $ret . 'text' );
151 $out->wrapWikiMsg( "<p class='error'>$1</p>", $ret );
153 $out->addHTML( $this->userForm( $this->mTarget
) );
158 $this->mTargetObj
= $ret;
160 // Set the 'relevant user' in the skin, so it displays links like Contributions,
161 // User logs, UserRights, etc.
162 $this->getSkin()->setRelevantUser( $this->mTargetObj
);
164 $context = new DerivativeContext( $this->getContext() );
165 $context->setTitle( $this->getPageTitle() ); // Remove subpage
166 $form = new HTMLForm( $this->getFormFields(), $context );
167 // By now we are supposed to be sure that $this->mTarget is a user name
168 $form->addPreText( $this->msg( 'emailpagetext', $this->mTarget
)->parse() );
169 $form->setSubmitTextMsg( 'emailsend' );
170 $form->setSubmitCallback( [ __CLASS__
, 'uiSubmit' ] );
171 $form->setWrapperLegendMsg( 'email-legend' );
174 if ( !Hooks
::run( 'EmailUserForm', [ &$form ] ) ) {
178 $result = $form->show();
180 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
181 $out->setPageTitle( $this->msg( 'emailsent' ) );
182 $out->addWikiMsg( 'emailsenttext', $this->mTarget
);
183 $out->returnToMain( false, $this->mTargetObj
->getUserPage() );
188 * Validate target User
190 * @param string $target Target user name
191 * @param User|null $sender User sending the email
192 * @return User|string User object on success or a string on error
194 public static function getTarget( $target, User
$sender = null ) {
195 if ( $sender === null ) {
196 wfDeprecated( __METHOD__
. ' without specifying the sending user', '1.30' );
199 if ( $target == '' ) {
200 wfDebug( "Target is empty.\n" );
205 $nu = User
::newFromName( $target );
206 $error = self
::validateTarget( $nu, $sender );
208 return $error ?
: $nu;
212 * Validate target User
214 * @param User $target Target user
215 * @param User|null $sender User sending the email
216 * @return string Error message or empty string if valid.
219 public static function validateTarget( $target, User
$sender = null ) {
220 if ( $sender === null ) {
221 wfDeprecated( __METHOD__
. ' without specifying the sending user', '1.30' );
224 if ( !$target instanceof User ||
!$target->getId() ) {
225 wfDebug( "Target is invalid user.\n" );
230 if ( !$target->isEmailConfirmed() ) {
231 wfDebug( "User has no valid email.\n" );
236 if ( !$target->canReceiveEmail() ) {
237 wfDebug( "User does not allow user emails.\n" );
239 return 'nowikiemail';
242 if ( $sender !== null && !$target->getOption( 'email-allow-new-users' ) &&
245 wfDebug( "User does not allow user emails from new users.\n" );
247 return 'nowikiemail';
250 if ( $sender !== null ) {
251 $blacklist = $target->getOption( 'email-blacklist', '' );
253 $blacklist = MultiUsernameFilter
::splitIds( $blacklist );
254 $lookup = CentralIdLookup
::factory();
255 $senderId = $lookup->centralIdFromLocalUser( $sender );
256 if ( $senderId !== 0 && in_array( $senderId, $blacklist ) ) {
257 wfDebug( "User does not allow user emails from this user.\n" );
259 return 'nowikiemail';
268 * Check whether a user is allowed to send email
271 * @param string $editToken Edit token
272 * @param Config|null $config optional for backwards compatibility
273 * @return string|null Null on success or string on error
275 public static function getPermissionsError( $user, $editToken, Config
$config = null ) {
276 if ( $config === null ) {
277 wfDebug( __METHOD__
. ' called without a Config instance passed to it' );
278 $config = MediaWikiServices
::getInstance()->getMainConfig();
280 if ( !$config->get( 'EnableEmail' ) ||
!$config->get( 'EnableUserEmail' ) ) {
281 return 'usermaildisabled';
284 // Run this before $user->isAllowed, to show appropriate message to anons (T160309)
285 if ( !$user->isEmailConfirmed() ) {
286 return 'mailnologin';
289 if ( !$user->isAllowed( 'sendemail' ) ) {
293 if ( $user->isBlockedFromEmailuser() ) {
294 wfDebug( "User is blocked from sending e-mail.\n" );
296 return "blockedemailuser";
299 // Check the ping limiter without incrementing it - we'll check it
300 // again later and increment it on a successful send
301 if ( $user->pingLimiter( 'emailuser', 0 ) ) {
302 wfDebug( "Ping limiter triggered.\n" );
304 return 'actionthrottledtext';
309 Hooks
::run( 'UserCanSendEmail', [ &$user, &$hookErr ] );
310 Hooks
::run( 'EmailUserPermissionsErrors', [ $user, $editToken, &$hookErr ] );
320 * Form to ask for target user name.
322 * @param string $name User name submitted.
323 * @return string Form asking for user name.
325 protected function userForm( $name ) {
326 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
327 $string = Html
::openElement(
329 [ 'method' => 'get', 'action' => wfScript(), 'id' => 'askusername' ]
331 Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
332 Html
::openElement( 'fieldset' ) .
333 Html
::rawElement( 'legend', null, $this->msg( 'emailtarget' )->parse() ) .
335 $this->msg( 'emailusername' )->text(),
343 'id' => 'emailusertarget',
344 'class' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
350 Html
::submitButton( $this->msg( 'emailusernamesubmit' )->text(), [] ) .
351 Html
::closeElement( 'fieldset' ) .
352 Html
::closeElement( 'form' ) . "\n";
358 * Submit callback for an HTMLForm object, will simply call submit().
362 * @param HTMLForm $form
363 * @return Status|bool
365 public static function uiSubmit( array $data, HTMLForm
$form ) {
366 return self
::submit( $data, $form->getContext() );
370 * Really send a mail. Permissions should have been checked using
371 * getPermissionsError(). It is probably also a good
372 * idea to check the edit token and ping limiter in advance.
375 * @param IContextSource $context
376 * @return Status|bool
378 public static function submit( array $data, IContextSource
$context ) {
379 $config = $context->getConfig();
381 $target = self
::getTarget( $data['Target'], $context->getUser() );
382 if ( !$target instanceof User
) {
383 // Messages used here: notargettext, noemailtext, nowikiemailtext
384 return Status
::newFatal( $target . 'text' );
387 $to = MailAddress
::newFromUser( $target );
388 $from = MailAddress
::newFromUser( $context->getUser() );
389 $subject = $data['Subject'];
390 $text = $data['Text'];
392 // Add a standard footer and trim up trailing newlines
393 $text = rtrim( $text ) . "\n\n-- \n";
394 $text .= $context->msg( 'emailuserfooter',
395 $from->name
, $to->name
)->inContentLanguage()->text();
397 // Check and increment the rate limits
398 if ( $context->getUser()->pingLimiter( 'emailuser' ) ) {
399 throw new ThrottledError();
403 if ( !Hooks
::run( 'EmailUser', [ &$to, &$from, &$subject, &$text, &$error ] ) ) {
404 if ( $error instanceof Status
) {
406 } elseif ( $error === false ||
$error === '' ||
$error === [] ) {
407 // Possibly to tell HTMLForm to pretend there was no submission?
409 } elseif ( $error === true ) {
410 // Hook sent the mail itself and indicates success?
411 return Status
::newGood();
412 } elseif ( is_array( $error ) ) {
413 $status = Status
::newGood();
414 foreach ( $error as $e ) {
415 $status->fatal( $e );
418 } elseif ( $error instanceof MessageSpecifier
) {
419 return Status
::newFatal( $error );
421 // Ugh. Either a raw HTML string, or something that's supposed
422 // to be treated like one.
423 $type = is_object( $error ) ?
get_class( $error ) : gettype( $error );
424 wfDeprecated( "EmailUser hook returning a $type as \$error", '1.29' );
425 return Status
::newFatal( new ApiRawMessage(
426 [ '$1', Message
::rawParam( (string)$error ) ], 'hookaborted'
431 if ( $config->get( 'UserEmailUseReplyTo' ) ) {
433 * Put the generic wiki autogenerated address in the From:
434 * header and reserve the user for Reply-To.
436 * This is a bit ugly, but will serve to differentiate
437 * wiki-borne mails from direct mails and protects against
438 * SPF and bounce problems with some mailers (see below).
440 $mailFrom = new MailAddress( $config->get( 'PasswordSender' ),
441 $context->msg( 'emailsender' )->inContentLanguage()->text() );
445 * Put the sending user's e-mail address in the From: header.
447 * This is clean-looking and convenient, but has issues.
448 * One is that it doesn't as clearly differentiate the wiki mail
449 * from "directly" sent mails.
451 * Another is that some mailers (like sSMTP) will use the From
452 * address as the envelope sender as well. For open sites this
453 * can cause mails to be flunked for SPF violations (since the
454 * wiki server isn't an authorized sender for various users'
455 * domains) as well as creating a privacy issue as bounces
456 * containing the recipient's e-mail address may get sent to
463 $status = UserMailer
::send( $to, $mailFrom, $subject, $text, [
464 'replyTo' => $replyTo,
467 if ( !$status->isGood() ) {
470 // if the user requested a copy of this mail, do this now,
471 // unless they are emailing themselves, in which case one
472 // copy of the message is sufficient.
473 if ( $data['CCMe'] && $to != $from ) {
476 $ccSubject = $context->msg( 'emailccsubject' )->rawParams(
477 $target->getName(), $subject )->text();
480 Hooks
::run( 'EmailUserCC', [ &$ccTo, &$ccFrom, &$ccSubject, &$ccText ] );
482 if ( $config->get( 'UserEmailUseReplyTo' ) ) {
483 $mailFrom = new MailAddress(
484 $config->get( 'PasswordSender' ),
485 $context->msg( 'emailsender' )->inContentLanguage()->text()
493 $ccStatus = UserMailer
::send(
494 $ccTo, $mailFrom, $ccSubject, $ccText, [
495 'replyTo' => $replyTo,
497 $status->merge( $ccStatus );
500 Hooks
::run( 'EmailUserComplete', [ $to, $from, $subject, $text ] );
507 * Return an array of subpages beginning with $search that this special page will accept.
509 * @param string $search Prefix to search for
510 * @param int $limit Maximum number of results to return (usually 10)
511 * @param int $offset Number of results to skip (usually 0)
512 * @return string[] Matching subpages
514 public function prefixSearchSubpages( $search, $limit, $offset ) {
515 $user = User
::newFromName( $search );
517 // No prefix suggestion for invalid user
520 // Autocomplete subpage as user list - public to allow caching
521 return UserNamePrefixSearch
::search( 'public', $search, $limit, $offset );
524 protected function getGroupName() {
529 * Builds an error message based on the block params
531 * @return ErrorPageError
533 private function getBlockedEmailError() {
534 $block = $this->getUser()->mBlock
;
535 $params = $block->getBlockErrorParams( $this->getContext() );
537 $msg = $block->isSitewide() ?
'blockedtext' : 'blocked-email-user';
538 return new ErrorPageError( 'blockedtitle', $msg, $params );