output: Narrow Title type hint to LinkTarget
[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 use MediaWiki\Preferences\MultiUsernameFilter;
25
26 /**
27 * A special page that allows users to send e-mails to other users
28 *
29 * @ingroup SpecialPage
30 */
31 class SpecialEmailUser extends UnlistedSpecialPage {
32 protected $mTarget;
33
34 /**
35 * @var User|string $mTargetObj
36 */
37 protected $mTargetObj;
38
39 public function __construct() {
40 parent::__construct( 'Emailuser' );
41 }
42
43 public function doesWrites() {
44 return true;
45 }
46
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();
51 }
52
53 return $this->msg( 'emailuser-title-target', $target->getName() )->text();
54 }
55
56 protected function getFormFields() {
57 $linkRenderer = $this->getLinkRenderer();
58 return [
59 'From' => [
60 'type' => 'info',
61 'raw' => 1,
62 'default' => $linkRenderer->makeLink(
63 $this->getUser()->getUserPage(),
64 $this->getUser()->getName()
65 ),
66 'label-message' => 'emailfrom',
67 'id' => 'mw-emailuser-sender',
68 ],
69 'To' => [
70 'type' => 'info',
71 'raw' => 1,
72 'default' => $linkRenderer->makeLink(
73 $this->mTargetObj->getUserPage(),
74 $this->mTargetObj->getName()
75 ),
76 'label-message' => 'emailto',
77 'id' => 'mw-emailuser-recipient',
78 ],
79 'Target' => [
80 'type' => 'hidden',
81 'default' => $this->mTargetObj->getName(),
82 ],
83 'Subject' => [
84 'type' => 'text',
85 'default' => $this->msg( 'defemailsubject',
86 $this->getUser()->getName() )->inContentLanguage()->text(),
87 'label-message' => 'emailsubject',
88 'maxlength' => 200,
89 'size' => 60,
90 'required' => true,
91 ],
92 'Text' => [
93 'type' => 'textarea',
94 'rows' => 20,
95 'label-message' => 'emailmessage',
96 'required' => true,
97 ],
98 'CCMe' => [
99 'type' => 'check',
100 'label-message' => 'emailccme',
101 'default' => $this->getUser()->getBoolOption( 'ccmeonemails' ),
102 ],
103 ];
104 }
105
106 public function execute( $par ) {
107 $out = $this->getOutput();
108 $request = $this->getRequest();
109 $out->addModuleStyles( 'mediawiki.special' );
110
111 $this->mTarget = $par ?? $request->getVal( 'wpTarget', $request->getVal( 'target', '' ) );
112
113 // Make sure, that HTMLForm uses the correct target.
114 $request->setVal( 'wpTarget', $this->mTarget );
115
116 // This needs to be below assignment of $this->mTarget because
117 // getDescription() needs it to determine the correct page title.
118 $this->setHeaders();
119 $this->outputHeader();
120
121 // error out if sending user cannot do this
122 $error = self::getPermissionsError(
123 $this->getUser(),
124 $this->getRequest()->getVal( 'wpEditToken' ),
125 $this->getConfig()
126 );
127
128 switch ( $error ) {
129 case null:
130 # Wahey!
131 break;
132 case 'badaccess':
133 throw new PermissionsError( 'sendemail' );
134 case 'blockedemailuser':
135 throw $this->getBlockedEmailError();
136 case 'actionthrottledtext':
137 throw new ThrottledError;
138 case 'mailnologin':
139 case 'usermaildisabled':
140 throw new ErrorPageError( $error, "{$error}text" );
141 default:
142 # It's a hook error
143 list( $title, $msg, $params ) = $error;
144 throw new ErrorPageError( $title, $msg, $params );
145 }
146
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 );
152
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"
156 // form, otherwise.
157 $this->mTargetObj = self::getTarget( $this->mTarget, $this->getUser() );
158 if ( !$this->mTargetObj instanceof User ) {
159 $this->userForm( $this->mTarget );
160 } else {
161 $this->sendEmailForm();
162 }
163 }
164
165 /**
166 * Validate target User
167 *
168 * @param string $target Target user name
169 * @param User $sender User sending the email
170 * @return User|string User object on success or a string on error
171 */
172 public static function getTarget( $target, User $sender ) {
173 if ( $target == '' ) {
174 wfDebug( "Target is empty.\n" );
175
176 return 'notarget';
177 }
178
179 $nu = User::newFromName( $target );
180 $error = self::validateTarget( $nu, $sender );
181
182 return $error ?: $nu;
183 }
184
185 /**
186 * Validate target User
187 *
188 * @param User $target Target user
189 * @param User $sender User sending the email
190 * @return string Error message or empty string if valid.
191 * @since 1.30
192 */
193 public static function validateTarget( $target, User $sender ) {
194 if ( !$target instanceof User || !$target->getId() ) {
195 wfDebug( "Target is invalid user.\n" );
196
197 return 'notarget';
198 }
199
200 if ( !$target->isEmailConfirmed() ) {
201 wfDebug( "User has no valid email.\n" );
202
203 return 'noemail';
204 }
205
206 if ( !$target->canReceiveEmail() ) {
207 wfDebug( "User does not allow user emails.\n" );
208
209 return 'nowikiemail';
210 }
211
212 if ( !$target->getOption( 'email-allow-new-users' ) && $sender->isNewbie() ) {
213 wfDebug( "User does not allow user emails from new users.\n" );
214
215 return 'nowikiemail';
216 }
217
218 $blacklist = $target->getOption( 'email-blacklist', '' );
219 if ( $blacklist ) {
220 $blacklist = MultiUsernameFilter::splitIds( $blacklist );
221 $lookup = CentralIdLookup::factory();
222 $senderId = $lookup->centralIdFromLocalUser( $sender );
223 if ( $senderId !== 0 && in_array( $senderId, $blacklist ) ) {
224 wfDebug( "User does not allow user emails from this user.\n" );
225
226 return 'nowikiemail';
227 }
228 }
229
230 return '';
231 }
232
233 /**
234 * Check whether a user is allowed to send email
235 *
236 * @param User $user
237 * @param string $editToken Edit token
238 * @param Config|null $config optional for backwards compatibility
239 * @return null|string|array Null on success, string on error, or array on
240 * hook error
241 */
242 public static function getPermissionsError( $user, $editToken, Config $config = null ) {
243 if ( $config === null ) {
244 wfDebug( __METHOD__ . ' called without a Config instance passed to it' );
245 $config = MediaWikiServices::getInstance()->getMainConfig();
246 }
247 if ( !$config->get( 'EnableEmail' ) || !$config->get( 'EnableUserEmail' ) ) {
248 return 'usermaildisabled';
249 }
250
251 // Run this before $user->isAllowed, to show appropriate message to anons (T160309)
252 if ( !$user->isEmailConfirmed() ) {
253 return 'mailnologin';
254 }
255
256 if ( !$user->isAllowed( 'sendemail' ) ) {
257 return 'badaccess';
258 }
259
260 if ( $user->isBlockedFromEmailuser() ) {
261 wfDebug( "User is blocked from sending e-mail.\n" );
262
263 return "blockedemailuser";
264 }
265
266 // Check the ping limiter without incrementing it - we'll check it
267 // again later and increment it on a successful send
268 if ( $user->pingLimiter( 'emailuser', 0 ) ) {
269 wfDebug( "Ping limiter triggered.\n" );
270
271 return 'actionthrottledtext';
272 }
273
274 $hookErr = false;
275
276 Hooks::run( 'UserCanSendEmail', [ &$user, &$hookErr ] );
277 Hooks::run( 'EmailUserPermissionsErrors', [ $user, $editToken, &$hookErr ] );
278
279 if ( $hookErr ) {
280 return $hookErr;
281 }
282
283 return null;
284 }
285
286 /**
287 * Form to ask for target user name.
288 *
289 * @param string $name User name submitted.
290 */
291 protected function userForm( $name ) {
292 $htmlForm = HTMLForm::factory( 'ooui', [
293 'Target' => [
294 'type' => 'user',
295 'exists' => true,
296 'label' => $this->msg( 'emailusername' )->text(),
297 'id' => 'emailusertarget',
298 'autofocus' => true,
299 'value' => $name,
300 ]
301 ], $this->getContext() );
302
303 $htmlForm
304 ->setMethod( 'post' )
305 ->setSubmitCallback( [ $this, 'sendEmailForm' ] )
306 ->setFormIdentifier( 'userForm' )
307 ->setId( 'askusername' )
308 ->setWrapperLegendMsg( 'emailtarget' )
309 ->setSubmitTextMsg( 'emailusernamesubmit' )
310 ->show();
311 }
312
313 public function sendEmailForm() {
314 $out = $this->getOutput();
315
316 $ret = $this->mTargetObj;
317 if ( !$ret instanceof User ) {
318 if ( $this->mTarget != '' ) {
319 // Messages used here: notargettext, noemailtext, nowikiemailtext
320 $ret = ( $ret == 'notarget' ) ? 'emailnotarget' : ( $ret . 'text' );
321 return Status::newFatal( $ret );
322 }
323 return false;
324 }
325
326 $htmlForm = HTMLForm::factory( 'ooui', $this->getFormFields(), $this->getContext() );
327 // By now we are supposed to be sure that $this->mTarget is a user name
328 $htmlForm
329 ->addPreText( $this->msg( 'emailpagetext', $this->mTarget )->parse() )
330 ->setSubmitTextMsg( 'emailsend' )
331 ->setSubmitCallback( [ __CLASS__, 'submit' ] )
332 ->setFormIdentifier( 'sendEmailForm' )
333 ->setWrapperLegendMsg( 'email-legend' )
334 ->loadData();
335
336 if ( !Hooks::run( 'EmailUserForm', [ &$htmlForm ] ) ) {
337 return false;
338 }
339
340 $result = $htmlForm->show();
341
342 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
343 $out->setPageTitle( $this->msg( 'emailsent' ) );
344 $out->addWikiMsg( 'emailsenttext', $this->mTarget );
345 $out->returnToMain( false, $ret->getUserPage() );
346 }
347 return true;
348 }
349
350 /**
351 * Really send a mail. Permissions should have been checked using
352 * getPermissionsError(). It is probably also a good
353 * idea to check the edit token and ping limiter in advance.
354 *
355 * @param array $data
356 * @param IContextSource $context
357 * @return Status|bool
358 */
359 public static function submit( array $data, IContextSource $context ) {
360 $config = $context->getConfig();
361
362 $target = self::getTarget( $data['Target'], $context->getUser() );
363 if ( !$target instanceof User ) {
364 // Messages used here: notargettext, noemailtext, nowikiemailtext
365 return Status::newFatal( $target . 'text' );
366 }
367
368 $to = MailAddress::newFromUser( $target );
369 $from = MailAddress::newFromUser( $context->getUser() );
370 $subject = $data['Subject'];
371 $text = $data['Text'];
372
373 // Add a standard footer and trim up trailing newlines
374 $text = rtrim( $text ) . "\n\n-- \n";
375 $text .= $context->msg( 'emailuserfooter',
376 $from->name, $to->name )->inContentLanguage()->text();
377
378 if ( $config->get( 'EnableSpecialMute' ) ) {
379 $specialMutePage = SpecialPage::getTitleFor( 'Mute', $context->getUser()->getName() );
380 $text .= "\n" . $context->msg(
381 'specialmute-email-footer',
382 $specialMutePage->getCanonicalURL(),
383 $context->getUser()->getName()
384 )->inContentLanguage()->text();
385 }
386
387 // Check and increment the rate limits
388 if ( $context->getUser()->pingLimiter( 'emailuser' ) ) {
389 throw new ThrottledError();
390 }
391
392 $error = false;
393 if ( !Hooks::run( 'EmailUser', [ &$to, &$from, &$subject, &$text, &$error ] ) ) {
394 if ( $error instanceof Status ) {
395 return $error;
396 } elseif ( $error === false || $error === '' || $error === [] ) {
397 // Possibly to tell HTMLForm to pretend there was no submission?
398 return false;
399 } elseif ( $error === true ) {
400 // Hook sent the mail itself and indicates success?
401 return Status::newGood();
402 } elseif ( is_array( $error ) ) {
403 $status = Status::newGood();
404 foreach ( $error as $e ) {
405 $status->fatal( $e );
406 }
407 return $status;
408 } elseif ( $error instanceof MessageSpecifier ) {
409 return Status::newFatal( $error );
410 } else {
411 // Ugh. Either a raw HTML string, or something that's supposed
412 // to be treated like one.
413 $type = is_object( $error ) ? get_class( $error ) : gettype( $error );
414 wfDeprecated( "EmailUser hook returning a $type as \$error", '1.29' );
415 return Status::newFatal( new ApiRawMessage(
416 [ '$1', Message::rawParam( (string)$error ) ], 'hookaborted'
417 ) );
418 }
419 }
420
421 if ( $config->get( 'UserEmailUseReplyTo' ) ) {
422 /**
423 * Put the generic wiki autogenerated address in the From:
424 * header and reserve the user for Reply-To.
425 *
426 * This is a bit ugly, but will serve to differentiate
427 * wiki-borne mails from direct mails and protects against
428 * SPF and bounce problems with some mailers (see below).
429 */
430 $mailFrom = new MailAddress( $config->get( 'PasswordSender' ),
431 $context->msg( 'emailsender' )->inContentLanguage()->text() );
432 $replyTo = $from;
433 } else {
434 /**
435 * Put the sending user's e-mail address in the From: header.
436 *
437 * This is clean-looking and convenient, but has issues.
438 * One is that it doesn't as clearly differentiate the wiki mail
439 * from "directly" sent mails.
440 *
441 * Another is that some mailers (like sSMTP) will use the From
442 * address as the envelope sender as well. For open sites this
443 * can cause mails to be flunked for SPF violations (since the
444 * wiki server isn't an authorized sender for various users'
445 * domains) as well as creating a privacy issue as bounces
446 * containing the recipient's e-mail address may get sent to
447 * the sending user.
448 */
449 $mailFrom = $from;
450 $replyTo = null;
451 }
452
453 $status = UserMailer::send( $to, $mailFrom, $subject, $text, [
454 'replyTo' => $replyTo,
455 ] );
456
457 if ( !$status->isGood() ) {
458 return $status;
459 } else {
460 // if the user requested a copy of this mail, do this now,
461 // unless they are emailing themselves, in which case one
462 // copy of the message is sufficient.
463 if ( $data['CCMe'] && $to != $from ) {
464 $ccTo = $from;
465 $ccFrom = $from;
466 $ccSubject = $context->msg( 'emailccsubject' )->plaintextParams(
467 $target->getName(), $subject )->text();
468 $ccText = $text;
469
470 Hooks::run( 'EmailUserCC', [ &$ccTo, &$ccFrom, &$ccSubject, &$ccText ] );
471
472 if ( $config->get( 'UserEmailUseReplyTo' ) ) {
473 $mailFrom = new MailAddress(
474 $config->get( 'PasswordSender' ),
475 $context->msg( 'emailsender' )->inContentLanguage()->text()
476 );
477 $replyTo = $ccFrom;
478 } else {
479 $mailFrom = $ccFrom;
480 $replyTo = null;
481 }
482
483 $ccStatus = UserMailer::send(
484 $ccTo, $mailFrom, $ccSubject, $ccText, [
485 'replyTo' => $replyTo,
486 ] );
487 $status->merge( $ccStatus );
488 }
489
490 Hooks::run( 'EmailUserComplete', [ $to, $from, $subject, $text ] );
491
492 return $status;
493 }
494 }
495
496 /**
497 * Return an array of subpages beginning with $search that this special page will accept.
498 *
499 * @param string $search Prefix to search for
500 * @param int $limit Maximum number of results to return (usually 10)
501 * @param int $offset Number of results to skip (usually 0)
502 * @return string[] Matching subpages
503 */
504 public function prefixSearchSubpages( $search, $limit, $offset ) {
505 $user = User::newFromName( $search );
506 if ( !$user ) {
507 // No prefix suggestion for invalid user
508 return [];
509 }
510 // Autocomplete subpage as user list - public to allow caching
511 return UserNamePrefixSearch::search( 'public', $search, $limit, $offset );
512 }
513
514 protected function getGroupName() {
515 return 'users';
516 }
517
518 /**
519 * Builds an error message based on the block params
520 *
521 * @return ErrorPageError
522 */
523 private function getBlockedEmailError() {
524 $block = $this->getUser()->mBlock;
525 $params = $block->getBlockErrorParams( $this->getContext() );
526
527 $msg = $block->isSitewide() ? 'blockedtext' : 'blocked-email-user';
528 return new ErrorPageError( 'blockedtitle', $msg, $params );
529 }
530 }