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|string|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|string|bool Status object, or potentially a String on error
323 * or maybe even true on success if anything uses the EmailUser hook.
325 public static function submit( array $data, IContextSource
$context ) {
326 $config = $context->getConfig();
328 $target = self
::getTarget( $data['Target'] );
329 if ( !$target instanceof User
) {
330 // Messages used here: notargettext, noemailtext, nowikiemailtext
331 return $context->msg( $target . 'text' )->parseAsBlock();
334 $to = MailAddress
::newFromUser( $target );
335 $from = MailAddress
::newFromUser( $context->getUser() );
336 $subject = $data['Subject'];
337 $text = $data['Text'];
339 // Add a standard footer and trim up trailing newlines
340 $text = rtrim( $text ) . "\n\n-- \n";
341 $text .= $context->msg( 'emailuserfooter',
342 $from->name
, $to->name
)->inContentLanguage()->text();
345 if ( !Hooks
::run( 'EmailUser', [ &$to, &$from, &$subject, &$text, &$error ] ) ) {
349 if ( $config->get( 'UserEmailUseReplyTo' ) ) {
351 * Put the generic wiki autogenerated address in the From:
352 * header and reserve the user for Reply-To.
354 * This is a bit ugly, but will serve to differentiate
355 * wiki-borne mails from direct mails and protects against
356 * SPF and bounce problems with some mailers (see below).
358 $mailFrom = new MailAddress( $config->get( 'PasswordSender' ),
359 wfMessage( 'emailsender' )->inContentLanguage()->text() );
363 * Put the sending user's e-mail address in the From: header.
365 * This is clean-looking and convenient, but has issues.
366 * One is that it doesn't as clearly differentiate the wiki mail
367 * from "directly" sent mails.
369 * Another is that some mailers (like sSMTP) will use the From
370 * address as the envelope sender as well. For open sites this
371 * can cause mails to be flunked for SPF violations (since the
372 * wiki server isn't an authorized sender for various users'
373 * domains) as well as creating a privacy issue as bounces
374 * containing the recipient's e-mail address may get sent to
381 $status = UserMailer
::send( $to, $mailFrom, $subject, $text, [
382 'replyTo' => $replyTo,
385 if ( !$status->isGood() ) {
388 // if the user requested a copy of this mail, do this now,
389 // unless they are emailing themselves, in which case one
390 // copy of the message is sufficient.
391 if ( $data['CCMe'] && $to != $from ) {
394 $ccSubject = $context->msg( 'emailccsubject' )->rawParams(
395 $target->getName(), $subject )->text();
398 Hooks
::run( 'EmailUserCC', [ &$ccTo, &$ccFrom, &$ccSubject, &$ccText ] );
400 if ( $config->get( 'UserEmailUseReplyTo' ) ) {
401 $mailFrom = new MailAddress(
402 $config->get( 'PasswordSender' ),
403 wfMessage( 'emailsender' )->inContentLanguage()->text()
411 $ccStatus = UserMailer
::send(
412 $ccTo, $mailFrom, $ccSubject, $ccText, [
413 'replyTo' => $replyTo,
415 $status->merge( $ccStatus );
418 Hooks
::run( 'EmailUserComplete', [ $to, $from, $subject, $text ] );
425 * Return an array of subpages beginning with $search that this special page will accept.
427 * @param string $search Prefix to search for
428 * @param int $limit Maximum number of results to return (usually 10)
429 * @param int $offset Number of results to skip (usually 0)
430 * @return string[] Matching subpages
432 public function prefixSearchSubpages( $search, $limit, $offset ) {
433 $user = User
::newFromName( $search );
435 // No prefix suggestion for invalid user
438 // Autocomplete subpage as user list - public to allow caching
439 return UserNamePrefixSearch
::search( 'public', $search, $limit, $offset );
442 protected function getGroupName() {