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',
95 'label-message' => 'emailmessage',
100 'label-message' => 'emailccme',
101 'default' => $this->getUser()->getBoolOption( 'ccmeonemails' ),
106 public function execute( $par ) {
107 $out = $this->getOutput();
108 $request = $this->getRequest();
109 $out->addModuleStyles( 'mediawiki.special' );
111 $this->mTarget
= $par ??
$request->getVal( 'wpTarget', $request->getVal( 'target', '' ) );
113 // Make sure, that HTMLForm uses the correct target.
114 $request->setVal( 'wpTarget', $this->mTarget
);
116 // This needs to be below assignment of $this->mTarget because
117 // getDescription() needs it to determine the correct page title.
119 $this->outputHeader();
121 // error out if sending user cannot do this
122 $error = self
::getPermissionsError(
124 $this->getRequest()->getVal( 'wpEditToken' ),
133 throw new PermissionsError( 'sendemail' );
134 case 'blockedemailuser':
135 throw $this->getBlockedEmailError();
136 case 'actionthrottledtext':
137 throw new ThrottledError
;
139 case 'usermaildisabled':
140 throw new ErrorPageError( $error, "{$error}text" );
143 list( $title, $msg, $params ) = $error;
144 throw new ErrorPageError( $title, $msg, $params );
147 // Make sure, that a submitted form isn't submitted to a subpage (which could be
148 // a non-existing username)
149 $context = new DerivativeContext( $this->getContext() );
150 $context->setTitle( $this->getPageTitle() ); // Remove subpage
151 $this->setContext( $context );
153 // A little hack: HTMLForm will check $this->mTarget only, if the form was posted, not
154 // if the user opens Special:EmailUser/Florian (e.g.). So check, if the user did that
155 // and show the "Send email to user" form directly, if so. Show the "enter username"
157 $this->mTargetObj
= self
::getTarget( $this->mTarget
, $this->getUser() );
158 if ( !$this->mTargetObj
instanceof User
) {
159 $this->userForm( $this->mTarget
);
161 $this->sendEmailForm();
166 * Validate target User
168 * @param string $target Target user name
169 * @param User|null $sender User sending the email
170 * @return User|string User object on success or a string on error
172 public static function getTarget( $target, User
$sender = null ) {
173 if ( $sender === null ) {
174 wfDeprecated( __METHOD__
. ' without specifying the sending user', '1.30' );
177 if ( $target == '' ) {
178 wfDebug( "Target is empty.\n" );
183 $nu = User
::newFromName( $target );
184 $error = self
::validateTarget( $nu, $sender );
186 return $error ?
: $nu;
190 * Validate target User
192 * @param User $target Target user
193 * @param User|null $sender User sending the email
194 * @return string Error message or empty string if valid.
197 public static function validateTarget( $target, User
$sender = null ) {
198 if ( $sender === null ) {
199 wfDeprecated( __METHOD__
. ' without specifying the sending user', '1.30' );
202 if ( !$target instanceof User ||
!$target->getId() ) {
203 wfDebug( "Target is invalid user.\n" );
208 if ( !$target->isEmailConfirmed() ) {
209 wfDebug( "User has no valid email.\n" );
214 if ( !$target->canReceiveEmail() ) {
215 wfDebug( "User does not allow user emails.\n" );
217 return 'nowikiemail';
220 if ( $sender !== null && !$target->getOption( 'email-allow-new-users' ) &&
223 wfDebug( "User does not allow user emails from new users.\n" );
225 return 'nowikiemail';
228 if ( $sender !== null ) {
229 $blacklist = $target->getOption( 'email-blacklist', '' );
231 $blacklist = MultiUsernameFilter
::splitIds( $blacklist );
232 $lookup = CentralIdLookup
::factory();
233 $senderId = $lookup->centralIdFromLocalUser( $sender );
234 if ( $senderId !== 0 && in_array( $senderId, $blacklist ) ) {
235 wfDebug( "User does not allow user emails from this user.\n" );
237 return 'nowikiemail';
246 * Check whether a user is allowed to send email
249 * @param string $editToken Edit token
250 * @param Config|null $config optional for backwards compatibility
251 * @return string|null Null on success or string on error
253 public static function getPermissionsError( $user, $editToken, Config
$config = null ) {
254 if ( $config === null ) {
255 wfDebug( __METHOD__
. ' called without a Config instance passed to it' );
256 $config = MediaWikiServices
::getInstance()->getMainConfig();
258 if ( !$config->get( 'EnableEmail' ) ||
!$config->get( 'EnableUserEmail' ) ) {
259 return 'usermaildisabled';
262 // Run this before $user->isAllowed, to show appropriate message to anons (T160309)
263 if ( !$user->isEmailConfirmed() ) {
264 return 'mailnologin';
267 if ( !$user->isAllowed( 'sendemail' ) ) {
271 if ( $user->isBlockedFromEmailuser() ) {
272 wfDebug( "User is blocked from sending e-mail.\n" );
274 return "blockedemailuser";
277 // Check the ping limiter without incrementing it - we'll check it
278 // again later and increment it on a successful send
279 if ( $user->pingLimiter( 'emailuser', 0 ) ) {
280 wfDebug( "Ping limiter triggered.\n" );
282 return 'actionthrottledtext';
287 Hooks
::run( 'UserCanSendEmail', [ &$user, &$hookErr ] );
288 Hooks
::run( 'EmailUserPermissionsErrors', [ $user, $editToken, &$hookErr ] );
298 * Form to ask for target user name.
300 * @param string $name User name submitted.
302 protected function userForm( $name ) {
303 $htmlForm = HTMLForm
::factory( 'ooui', [
307 'label' => $this->msg( 'emailusername' )->text(),
308 'id' => 'emailusertarget',
312 ], $this->getContext() );
315 ->setMethod( 'post' )
316 ->setSubmitCallback( [ $this, 'sendEmailForm' ] )
317 ->setFormIdentifier( 'userForm' )
318 ->setId( 'askusername' )
319 ->setWrapperLegendMsg( 'emailtarget' )
320 ->setSubmitTextMsg( 'emailusernamesubmit' )
324 public function sendEmailForm() {
325 $out = $this->getOutput();
327 $ret = $this->mTargetObj
;
328 if ( !$ret instanceof User
) {
329 if ( $this->mTarget
!= '' ) {
330 // Messages used here: notargettext, noemailtext, nowikiemailtext
331 $ret = ( $ret == 'notarget' ) ?
'emailnotarget' : ( $ret . 'text' );
332 return Status
::newFatal( $ret );
337 $htmlForm = HTMLForm
::factory( 'ooui', $this->getFormFields(), $this->getContext() );
338 // By now we are supposed to be sure that $this->mTarget is a user name
340 ->addPreText( $this->msg( 'emailpagetext', $this->mTarget
)->parse() )
341 ->setSubmitTextMsg( 'emailsend' )
342 ->setSubmitCallback( [ __CLASS__
, 'submit' ] )
343 ->setFormIdentifier( 'sendEmailForm' )
344 ->setWrapperLegendMsg( 'email-legend' )
347 if ( !Hooks
::run( 'EmailUserForm', [ &$htmlForm ] ) ) {
351 $result = $htmlForm->show();
353 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
354 $out->setPageTitle( $this->msg( 'emailsent' ) );
355 $out->addWikiMsg( 'emailsenttext', $this->mTarget
);
356 $out->returnToMain( false, $ret->getUserPage() );
362 * Really send a mail. Permissions should have been checked using
363 * getPermissionsError(). It is probably also a good
364 * idea to check the edit token and ping limiter in advance.
367 * @param IContextSource $context
368 * @return Status|bool
370 public static function submit( array $data, IContextSource
$context ) {
371 $config = $context->getConfig();
373 $target = self
::getTarget( $data['Target'], $context->getUser() );
374 if ( !$target instanceof User
) {
375 // Messages used here: notargettext, noemailtext, nowikiemailtext
376 return Status
::newFatal( $target . 'text' );
379 $to = MailAddress
::newFromUser( $target );
380 $from = MailAddress
::newFromUser( $context->getUser() );
381 $subject = $data['Subject'];
382 $text = $data['Text'];
384 // Add a standard footer and trim up trailing newlines
385 $text = rtrim( $text ) . "\n\n-- \n";
386 $text .= $context->msg( 'emailuserfooter',
387 $from->name
, $to->name
)->inContentLanguage()->text();
389 // Check and increment the rate limits
390 if ( $context->getUser()->pingLimiter( 'emailuser' ) ) {
391 throw new ThrottledError();
395 if ( !Hooks
::run( 'EmailUser', [ &$to, &$from, &$subject, &$text, &$error ] ) ) {
396 if ( $error instanceof Status
) {
398 } elseif ( $error === false ||
$error === '' ||
$error === [] ) {
399 // Possibly to tell HTMLForm to pretend there was no submission?
401 } elseif ( $error === true ) {
402 // Hook sent the mail itself and indicates success?
403 return Status
::newGood();
404 } elseif ( is_array( $error ) ) {
405 $status = Status
::newGood();
406 foreach ( $error as $e ) {
407 $status->fatal( $e );
410 } elseif ( $error instanceof MessageSpecifier
) {
411 return Status
::newFatal( $error );
413 // Ugh. Either a raw HTML string, or something that's supposed
414 // to be treated like one.
415 $type = is_object( $error ) ?
get_class( $error ) : gettype( $error );
416 wfDeprecated( "EmailUser hook returning a $type as \$error", '1.29' );
417 return Status
::newFatal( new ApiRawMessage(
418 [ '$1', Message
::rawParam( (string)$error ) ], 'hookaborted'
423 if ( $config->get( 'UserEmailUseReplyTo' ) ) {
425 * Put the generic wiki autogenerated address in the From:
426 * header and reserve the user for Reply-To.
428 * This is a bit ugly, but will serve to differentiate
429 * wiki-borne mails from direct mails and protects against
430 * SPF and bounce problems with some mailers (see below).
432 $mailFrom = new MailAddress( $config->get( 'PasswordSender' ),
433 $context->msg( 'emailsender' )->inContentLanguage()->text() );
437 * Put the sending user's e-mail address in the From: header.
439 * This is clean-looking and convenient, but has issues.
440 * One is that it doesn't as clearly differentiate the wiki mail
441 * from "directly" sent mails.
443 * Another is that some mailers (like sSMTP) will use the From
444 * address as the envelope sender as well. For open sites this
445 * can cause mails to be flunked for SPF violations (since the
446 * wiki server isn't an authorized sender for various users'
447 * domains) as well as creating a privacy issue as bounces
448 * containing the recipient's e-mail address may get sent to
455 $status = UserMailer
::send( $to, $mailFrom, $subject, $text, [
456 'replyTo' => $replyTo,
459 if ( !$status->isGood() ) {
462 // if the user requested a copy of this mail, do this now,
463 // unless they are emailing themselves, in which case one
464 // copy of the message is sufficient.
465 if ( $data['CCMe'] && $to != $from ) {
468 $ccSubject = $context->msg( 'emailccsubject' )->plaintextParams(
469 $target->getName(), $subject )->text();
472 Hooks
::run( 'EmailUserCC', [ &$ccTo, &$ccFrom, &$ccSubject, &$ccText ] );
474 if ( $config->get( 'UserEmailUseReplyTo' ) ) {
475 $mailFrom = new MailAddress(
476 $config->get( 'PasswordSender' ),
477 $context->msg( 'emailsender' )->inContentLanguage()->text()
485 $ccStatus = UserMailer
::send(
486 $ccTo, $mailFrom, $ccSubject, $ccText, [
487 'replyTo' => $replyTo,
489 $status->merge( $ccStatus );
492 Hooks
::run( 'EmailUserComplete', [ $to, $from, $subject, $text ] );
499 * Return an array of subpages beginning with $search that this special page will accept.
501 * @param string $search Prefix to search for
502 * @param int $limit Maximum number of results to return (usually 10)
503 * @param int $offset Number of results to skip (usually 0)
504 * @return string[] Matching subpages
506 public function prefixSearchSubpages( $search, $limit, $offset ) {
507 $user = User
::newFromName( $search );
509 // No prefix suggestion for invalid user
512 // Autocomplete subpage as user list - public to allow caching
513 return UserNamePrefixSearch
::search( 'public', $search, $limit, $offset );
516 protected function getGroupName() {
521 * Builds an error message based on the block params
523 * @return ErrorPageError
525 private function getBlockedEmailError() {
526 $block = $this->getUser()->mBlock
;
527 $params = $block->getBlockErrorParams( $this->getContext() );
529 $msg = $block->isSitewide() ?
'blockedtext' : 'blocked-email-user';
530 return new ErrorPageError( 'blockedtitle', $msg, $params );