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