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
;
26 * A special page that allows users to send e-mails to other users
28 * @ingroup SpecialPage
30 class SpecialEmailUser
extends UnlistedSpecialPage
{
34 * @var User|string $mTargetObj
36 protected $mTargetObj;
38 public function __construct() {
39 parent
::__construct( 'Emailuser' );
42 public function doesWrites() {
46 public function getDescription() {
47 $target = self
::getTarget( $this->mTarget
);
48 if ( !$target instanceof User
) {
49 return $this->msg( 'emailuser-title-notarget' )->text();
52 return $this->msg( 'emailuser-title-target', $target->getName() )->text();
55 protected function getFormFields() {
60 'default' => Linker
::link(
61 $this->getUser()->getUserPage(),
62 htmlspecialchars( $this->getUser()->getName() )
64 'label-message' => 'emailfrom',
65 'id' => 'mw-emailuser-sender',
70 'default' => Linker
::link(
71 $this->mTargetObj
->getUserPage(),
72 htmlspecialchars( $this->mTargetObj
->getName() )
74 'label-message' => 'emailto',
75 'id' => 'mw-emailuser-recipient',
79 'default' => $this->mTargetObj
->getName(),
83 'default' => $this->msg( 'defemailsubject',
84 $this->getUser()->getName() )->inContentLanguage()->text(),
85 'label-message' => 'emailsubject',
94 'label-message' => 'emailmessage',
99 'label-message' => 'emailccme',
100 'default' => $this->getUser()->getBoolOption( 'ccmeonemails' ),
105 public function execute( $par ) {
106 $out = $this->getOutput();
107 $out->addModuleStyles( 'mediawiki.special' );
109 $this->mTarget
= is_null( $par )
110 ?
$this->getRequest()->getVal( 'wpTarget', $this->getRequest()->getVal( 'target', '' ) )
113 // This needs to be below assignment of $this->mTarget because
114 // getDescription() needs it to determine the correct page title.
116 $this->outputHeader();
118 // error out if sending user cannot do this
119 $error = self
::getPermissionsError(
121 $this->getRequest()->getVal( 'wpEditToken' ),
130 throw new PermissionsError( 'sendemail' );
131 case 'blockedemailuser':
132 throw new UserBlockedError( $this->getUser()->mBlock
);
133 case 'actionthrottledtext':
134 throw new ThrottledError
;
136 case 'usermaildisabled':
137 throw new ErrorPageError( $error, "{$error}text" );
140 list( $title, $msg, $params ) = $error;
141 throw new ErrorPageError( $title, $msg, $params );
143 // Got a valid target user name? Else ask for one.
144 $ret = self
::getTarget( $this->mTarget
);
145 if ( !$ret instanceof User
) {
146 if ( $this->mTarget
!= '' ) {
147 // Messages used here: notargettext, noemailtext, nowikiemailtext
148 $ret = ( $ret == 'notarget' ) ?
'emailnotarget' : ( $ret . 'text' );
149 $out->wrapWikiMsg( "<p class='error'>$1</p>", $ret );
151 $out->addHTML( $this->userForm( $this->mTarget
) );
156 $this->mTargetObj
= $ret;
158 // Set the 'relevant user' in the skin, so it displays links like Contributions,
159 // User logs, UserRights, etc.
160 $this->getSkin()->setRelevantUser( $this->mTargetObj
);
162 $context = new DerivativeContext( $this->getContext() );
163 $context->setTitle( $this->getPageTitle() ); // Remove subpage
164 $form = new HTMLForm( $this->getFormFields(), $context );
165 // By now we are supposed to be sure that $this->mTarget is a user name
166 $form->addPreText( $this->msg( 'emailpagetext', $this->mTarget
)->parse() );
167 $form->setSubmitTextMsg( 'emailsend' );
168 $form->setSubmitCallback( [ __CLASS__
, 'uiSubmit' ] );
169 $form->setWrapperLegendMsg( 'email-legend' );
172 if ( !Hooks
::run( 'EmailUserForm', [ &$form ] ) ) {
176 $result = $form->show();
178 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
179 $out->setPageTitle( $this->msg( 'emailsent' ) );
180 $out->addWikiMsg( 'emailsenttext', $this->mTarget
);
181 $out->returnToMain( false, $this->mTargetObj
->getUserPage() );
186 * Validate target User
188 * @param string $target Target user name
189 * @return User User object on success or a string on error
191 public static function getTarget( $target ) {
192 if ( $target == '' ) {
193 wfDebug( "Target is empty.\n" );
198 $nu = User
::newFromName( $target );
199 if ( !$nu instanceof User ||
!$nu->getId() ) {
200 wfDebug( "Target is invalid user.\n" );
203 } elseif ( !$nu->isEmailConfirmed() ) {
204 wfDebug( "User has no valid email.\n" );
207 } elseif ( !$nu->canReceiveEmail() ) {
208 wfDebug( "User does not allow user emails.\n" );
210 return 'nowikiemail';
217 * Check whether a user is allowed to send email
220 * @param string $editToken Edit token
221 * @param Config $config optional for backwards compatibility
222 * @return string|null Null on success or string on error
224 public static function getPermissionsError( $user, $editToken, Config
$config = null ) {
225 if ( $config === null ) {
226 wfDebug( __METHOD__
. ' called without a Config instance passed to it' );
227 $config = MediaWikiServices
::getInstance()->getMainConfig();
229 if ( !$config->get( 'EnableEmail' ) ||
!$config->get( 'EnableUserEmail' ) ) {
230 return 'usermaildisabled';
233 if ( !$user->isAllowed( 'sendemail' ) ) {
237 if ( !$user->isEmailConfirmed() ) {
238 return 'mailnologin';
241 if ( $user->isBlockedFromEmailuser() ) {
242 wfDebug( "User is blocked from sending e-mail.\n" );
244 return "blockedemailuser";
247 if ( $user->pingLimiter( 'emailuser' ) ) {
248 wfDebug( "Ping limiter triggered.\n" );
250 return 'actionthrottledtext';
255 Hooks
::run( 'UserCanSendEmail', [ &$user, &$hookErr ] );
256 Hooks
::run( 'EmailUserPermissionsErrors', [ $user, $editToken, &$hookErr ] );
266 * Form to ask for target user name.
268 * @param string $name User name submitted.
269 * @return string Form asking for user name.
271 protected function userForm( $name ) {
272 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
273 $string = Html
::openElement(
275 [ 'method' => 'get', 'action' => wfScript(), 'id' => 'askusername' ]
277 Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
278 Html
::openElement( 'fieldset' ) .
279 Html
::rawElement( 'legend', null, $this->msg( 'emailtarget' )->parse() ) .
281 $this->msg( 'emailusername' )->text(),
289 'id' => 'emailusertarget',
290 'class' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
296 Html
::submitButton( $this->msg( 'emailusernamesubmit' )->text(), [] ) .
297 Html
::closeElement( 'fieldset' ) .
298 Html
::closeElement( 'form' ) . "\n";
304 * Submit callback for an HTMLForm object, will simply call submit().
308 * @param HTMLForm $form
309 * @return Status|bool
311 public static function uiSubmit( array $data, HTMLForm
$form ) {
312 return self
::submit( $data, $form->getContext() );
316 * Really send a mail. Permissions should have been checked using
317 * getPermissionsError(). It is probably also a good
318 * idea to check the edit token and ping limiter in advance.
321 * @param IContextSource $context
322 * @return Status|bool
324 public static function submit( array $data, IContextSource
$context ) {
325 $config = $context->getConfig();
327 $target = self
::getTarget( $data['Target'] );
328 if ( !$target instanceof User
) {
329 // Messages used here: notargettext, noemailtext, nowikiemailtext
330 return Status
::newFatal( $target . 'text' );
333 $to = MailAddress
::newFromUser( $target );
334 $from = MailAddress
::newFromUser( $context->getUser() );
335 $subject = $data['Subject'];
336 $text = $data['Text'];
338 // Add a standard footer and trim up trailing newlines
339 $text = rtrim( $text ) . "\n\n-- \n";
340 $text .= $context->msg( 'emailuserfooter',
341 $from->name
, $to->name
)->inContentLanguage()->text();
344 if ( !Hooks
::run( 'EmailUser', [ &$to, &$from, &$subject, &$text, &$error ] ) ) {
345 if ( $error instanceof Status
) {
347 } elseif ( $error === false ||
$error === '' ||
$error === [] ) {
348 // Possibly to tell HTMLForm to pretend there was no submission?
350 } elseif ( $error === true ) {
351 // Hook sent the mail itself and indicates success?
352 return Status
::newGood();
353 } elseif ( is_array( $error ) ) {
354 $status = Status
::newGood();
355 foreach ( $error as $e ) {
356 $status->fatal( $e );
359 } elseif ( $error instanceof MessageSpecifier
) {
360 return Status
::newFatal( $error );
362 // Ugh. Either a raw HTML string, or something that's supposed
363 // to be treated like one.
364 $type = is_object( $error ) ?
get_class( $error ) : gettype( $error );
365 wfDeprecated( "EmailUser hook returning a $type as \$error", '1.29' );
366 return Status
::newFatal( new ApiRawMessage(
367 [ '$1', Message
::rawParam( (string)$error ) ], 'hookaborted'
372 if ( $config->get( 'UserEmailUseReplyTo' ) ) {
374 * Put the generic wiki autogenerated address in the From:
375 * header and reserve the user for Reply-To.
377 * This is a bit ugly, but will serve to differentiate
378 * wiki-borne mails from direct mails and protects against
379 * SPF and bounce problems with some mailers (see below).
381 $mailFrom = new MailAddress( $config->get( 'PasswordSender' ),
382 wfMessage( 'emailsender' )->inContentLanguage()->text() );
386 * Put the sending user's e-mail address in the From: header.
388 * This is clean-looking and convenient, but has issues.
389 * One is that it doesn't as clearly differentiate the wiki mail
390 * from "directly" sent mails.
392 * Another is that some mailers (like sSMTP) will use the From
393 * address as the envelope sender as well. For open sites this
394 * can cause mails to be flunked for SPF violations (since the
395 * wiki server isn't an authorized sender for various users'
396 * domains) as well as creating a privacy issue as bounces
397 * containing the recipient's e-mail address may get sent to
404 $status = UserMailer
::send( $to, $mailFrom, $subject, $text, [
405 'replyTo' => $replyTo,
408 if ( !$status->isGood() ) {
411 // if the user requested a copy of this mail, do this now,
412 // unless they are emailing themselves, in which case one
413 // copy of the message is sufficient.
414 if ( $data['CCMe'] && $to != $from ) {
417 $ccSubject = $context->msg( 'emailccsubject' )->rawParams(
418 $target->getName(), $subject )->text();
421 Hooks
::run( 'EmailUserCC', [ &$ccTo, &$ccFrom, &$ccSubject, &$ccText ] );
423 if ( $config->get( 'UserEmailUseReplyTo' ) ) {
424 $mailFrom = new MailAddress(
425 $config->get( 'PasswordSender' ),
426 wfMessage( 'emailsender' )->inContentLanguage()->text()
434 $ccStatus = UserMailer
::send(
435 $ccTo, $mailFrom, $ccSubject, $ccText, [
436 'replyTo' => $replyTo,
438 $status->merge( $ccStatus );
441 Hooks
::run( 'EmailUserComplete', [ $to, $from, $subject, $text ] );
448 * Return an array of subpages beginning with $search that this special page will accept.
450 * @param string $search Prefix to search for
451 * @param int $limit Maximum number of results to return (usually 10)
452 * @param int $offset Number of results to skip (usually 0)
453 * @return string[] Matching subpages
455 public function prefixSearchSubpages( $search, $limit, $offset ) {
456 $user = User
::newFromName( $search );
458 // No prefix suggestion for invalid user
461 // Autocomplete subpage as user list - public to allow caching
462 return UserNamePrefixSearch
::search( 'public', $search, $limit, $offset );
465 protected function getGroupName() {