Merge "Don't fallback from uk to ru"
[lhc/web/wiklou.git] / includes / specials / SpecialEmailuser.php
1 <?php
2 /**
3 * Implements Special:Emailuser
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 * @ingroup SpecialPage
22 */
23 use MediaWiki\MediaWikiServices;
24
25 /**
26 * A special page that allows users to send e-mails to other users
27 *
28 * @ingroup SpecialPage
29 */
30 class SpecialEmailUser extends UnlistedSpecialPage {
31 protected $mTarget;
32
33 /**
34 * @var User|string $mTargetObj
35 */
36 protected $mTargetObj;
37
38 public function __construct() {
39 parent::__construct( 'Emailuser' );
40 }
41
42 public function doesWrites() {
43 return true;
44 }
45
46 public function getDescription() {
47 $target = self::getTarget( $this->mTarget );
48 if ( !$target instanceof User ) {
49 return $this->msg( 'emailuser-title-notarget' )->text();
50 }
51
52 return $this->msg( 'emailuser-title-target', $target->getName() )->text();
53 }
54
55 protected function getFormFields() {
56 return [
57 'From' => [
58 'type' => 'info',
59 'raw' => 1,
60 'default' => Linker::link(
61 $this->getUser()->getUserPage(),
62 htmlspecialchars( $this->getUser()->getName() )
63 ),
64 'label-message' => 'emailfrom',
65 'id' => 'mw-emailuser-sender',
66 ],
67 'To' => [
68 'type' => 'info',
69 'raw' => 1,
70 'default' => Linker::link(
71 $this->mTargetObj->getUserPage(),
72 htmlspecialchars( $this->mTargetObj->getName() )
73 ),
74 'label-message' => 'emailto',
75 'id' => 'mw-emailuser-recipient',
76 ],
77 'Target' => [
78 'type' => 'hidden',
79 'default' => $this->mTargetObj->getName(),
80 ],
81 'Subject' => [
82 'type' => 'text',
83 'default' => $this->msg( 'defemailsubject',
84 $this->getUser()->getName() )->inContentLanguage()->text(),
85 'label-message' => 'emailsubject',
86 'maxlength' => 200,
87 'size' => 60,
88 'required' => true,
89 ],
90 'Text' => [
91 'type' => 'textarea',
92 'rows' => 20,
93 'cols' => 80,
94 'label-message' => 'emailmessage',
95 'required' => true,
96 ],
97 'CCMe' => [
98 'type' => 'check',
99 'label-message' => 'emailccme',
100 'default' => $this->getUser()->getBoolOption( 'ccmeonemails' ),
101 ],
102 ];
103 }
104
105 public function execute( $par ) {
106 $out = $this->getOutput();
107 $out->addModuleStyles( 'mediawiki.special' );
108
109 $this->mTarget = is_null( $par )
110 ? $this->getRequest()->getVal( 'wpTarget', $this->getRequest()->getVal( 'target', '' ) )
111 : $par;
112
113 // This needs to be below assignment of $this->mTarget because
114 // getDescription() needs it to determine the correct page title.
115 $this->setHeaders();
116 $this->outputHeader();
117
118 // error out if sending user cannot do this
119 $error = self::getPermissionsError(
120 $this->getUser(),
121 $this->getRequest()->getVal( 'wpEditToken' ),
122 $this->getConfig()
123 );
124
125 switch ( $error ) {
126 case null:
127 # Wahey!
128 break;
129 case 'badaccess':
130 throw new PermissionsError( 'sendemail' );
131 case 'blockedemailuser':
132 throw new UserBlockedError( $this->getUser()->mBlock );
133 case 'actionthrottledtext':
134 throw new ThrottledError;
135 case 'mailnologin':
136 case 'usermaildisabled':
137 throw new ErrorPageError( $error, "{$error}text" );
138 default:
139 # It's a hook error
140 list( $title, $msg, $params ) = $error;
141 throw new ErrorPageError( $title, $msg, $params );
142 }
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 );
150 }
151 $out->addHTML( $this->userForm( $this->mTarget ) );
152
153 return;
154 }
155
156 $this->mTargetObj = $ret;
157
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 );
161
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' );
170 $form->loadData();
171
172 if ( !Hooks::run( 'EmailUserForm', [ &$form ] ) ) {
173 return;
174 }
175
176 $result = $form->show();
177
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() );
182 }
183 }
184
185 /**
186 * Validate target User
187 *
188 * @param string $target Target user name
189 * @return User User object on success or a string on error
190 */
191 public static function getTarget( $target ) {
192 if ( $target == '' ) {
193 wfDebug( "Target is empty.\n" );
194
195 return 'notarget';
196 }
197
198 $nu = User::newFromName( $target );
199 if ( !$nu instanceof User || !$nu->getId() ) {
200 wfDebug( "Target is invalid user.\n" );
201
202 return 'notarget';
203 } elseif ( !$nu->isEmailConfirmed() ) {
204 wfDebug( "User has no valid email.\n" );
205
206 return 'noemail';
207 } elseif ( !$nu->canReceiveEmail() ) {
208 wfDebug( "User does not allow user emails.\n" );
209
210 return 'nowikiemail';
211 }
212
213 return $nu;
214 }
215
216 /**
217 * Check whether a user is allowed to send email
218 *
219 * @param User $user
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
223 */
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();
228 }
229 if ( !$config->get( 'EnableEmail' ) || !$config->get( 'EnableUserEmail' ) ) {
230 return 'usermaildisabled';
231 }
232
233 if ( !$user->isAllowed( 'sendemail' ) ) {
234 return 'badaccess';
235 }
236
237 if ( !$user->isEmailConfirmed() ) {
238 return 'mailnologin';
239 }
240
241 if ( $user->isBlockedFromEmailuser() ) {
242 wfDebug( "User is blocked from sending e-mail.\n" );
243
244 return "blockedemailuser";
245 }
246
247 if ( $user->pingLimiter( 'emailuser' ) ) {
248 wfDebug( "Ping limiter triggered.\n" );
249
250 return 'actionthrottledtext';
251 }
252
253 $hookErr = false;
254
255 Hooks::run( 'UserCanSendEmail', [ &$user, &$hookErr ] );
256 Hooks::run( 'EmailUserPermissionsErrors', [ $user, $editToken, &$hookErr ] );
257
258 if ( $hookErr ) {
259 return $hookErr;
260 }
261
262 return null;
263 }
264
265 /**
266 * Form to ask for target user name.
267 *
268 * @param string $name User name submitted.
269 * @return string Form asking for user name.
270 */
271 protected function userForm( $name ) {
272 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
273 $string = Html::openElement(
274 'form',
275 [ 'method' => 'get', 'action' => wfScript(), 'id' => 'askusername' ]
276 ) .
277 Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
278 Html::openElement( 'fieldset' ) .
279 Html::rawElement( 'legend', null, $this->msg( 'emailtarget' )->parse() ) .
280 Html::label(
281 $this->msg( 'emailusername' )->text(),
282 'emailusertarget'
283 ) . '&#160;' .
284 Html::input(
285 'target',
286 $name,
287 'text',
288 [
289 'id' => 'emailusertarget',
290 'class' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
291 'autofocus' => true,
292 'size' => 30,
293 ]
294 ) .
295 ' ' .
296 Html::submitButton( $this->msg( 'emailusernamesubmit' )->text(), [] ) .
297 Html::closeElement( 'fieldset' ) .
298 Html::closeElement( 'form' ) . "\n";
299
300 return $string;
301 }
302
303 /**
304 * Submit callback for an HTMLForm object, will simply call submit().
305 *
306 * @since 1.20
307 * @param array $data
308 * @param HTMLForm $form
309 * @return Status|string|bool
310 */
311 public static function uiSubmit( array $data, HTMLForm $form ) {
312 return self::submit( $data, $form->getContext() );
313 }
314
315 /**
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.
319 *
320 * @param array $data
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.
324 */
325 public static function submit( array $data, IContextSource $context ) {
326 $config = $context->getConfig();
327
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();
332 }
333
334 $to = MailAddress::newFromUser( $target );
335 $from = MailAddress::newFromUser( $context->getUser() );
336 $subject = $data['Subject'];
337 $text = $data['Text'];
338
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();
343
344 $error = '';
345 if ( !Hooks::run( 'EmailUser', [ &$to, &$from, &$subject, &$text, &$error ] ) ) {
346 return $error;
347 }
348
349 if ( $config->get( 'UserEmailUseReplyTo' ) ) {
350 /**
351 * Put the generic wiki autogenerated address in the From:
352 * header and reserve the user for Reply-To.
353 *
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).
357 */
358 $mailFrom = new MailAddress( $config->get( 'PasswordSender' ),
359 wfMessage( 'emailsender' )->inContentLanguage()->text() );
360 $replyTo = $from;
361 } else {
362 /**
363 * Put the sending user's e-mail address in the From: header.
364 *
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.
368 *
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
375 * the sending user.
376 */
377 $mailFrom = $from;
378 $replyTo = null;
379 }
380
381 $status = UserMailer::send( $to, $mailFrom, $subject, $text, [
382 'replyTo' => $replyTo,
383 ] );
384
385 if ( !$status->isGood() ) {
386 return $status;
387 } else {
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 ) {
392 $ccTo = $from;
393 $ccFrom = $from;
394 $ccSubject = $context->msg( 'emailccsubject' )->rawParams(
395 $target->getName(), $subject )->text();
396 $ccText = $text;
397
398 Hooks::run( 'EmailUserCC', [ &$ccTo, &$ccFrom, &$ccSubject, &$ccText ] );
399
400 if ( $config->get( 'UserEmailUseReplyTo' ) ) {
401 $mailFrom = new MailAddress(
402 $config->get( 'PasswordSender' ),
403 wfMessage( 'emailsender' )->inContentLanguage()->text()
404 );
405 $replyTo = $ccFrom;
406 } else {
407 $mailFrom = $ccFrom;
408 $replyTo = null;
409 }
410
411 $ccStatus = UserMailer::send(
412 $ccTo, $mailFrom, $ccSubject, $ccText, [
413 'replyTo' => $replyTo,
414 ] );
415 $status->merge( $ccStatus );
416 }
417
418 Hooks::run( 'EmailUserComplete', [ $to, $from, $subject, $text ] );
419
420 return $status;
421 }
422 }
423
424 /**
425 * Return an array of subpages beginning with $search that this special page will accept.
426 *
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
431 */
432 public function prefixSearchSubpages( $search, $limit, $offset ) {
433 $user = User::newFromName( $search );
434 if ( !$user ) {
435 // No prefix suggestion for invalid user
436 return [];
437 }
438 // Autocomplete subpage as user list - public to allow caching
439 return UserNamePrefixSearch::search( 'public', $search, $limit, $offset );
440 }
441
442 protected function getGroupName() {
443 return 'users';
444 }
445 }