Merge "Declare dynamic properties"
[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 ( !MediaWikiServices::getInstance()
257 ->getPermissionManager()
258 ->userHasRight( $user, 'sendemail' )
259 ) {
260 return 'badaccess';
261 }
262
263 if ( $user->isBlockedFromEmailuser() ) {
264 wfDebug( "User is blocked from sending e-mail.\n" );
265
266 return "blockedemailuser";
267 }
268
269 // Check the ping limiter without incrementing it - we'll check it
270 // again later and increment it on a successful send
271 if ( $user->pingLimiter( 'emailuser', 0 ) ) {
272 wfDebug( "Ping limiter triggered.\n" );
273
274 return 'actionthrottledtext';
275 }
276
277 $hookErr = false;
278
279 Hooks::run( 'UserCanSendEmail', [ &$user, &$hookErr ] );
280 Hooks::run( 'EmailUserPermissionsErrors', [ $user, $editToken, &$hookErr ] );
281
282 if ( $hookErr ) {
283 return $hookErr;
284 }
285
286 return null;
287 }
288
289 /**
290 * Form to ask for target user name.
291 *
292 * @param string $name User name submitted.
293 */
294 protected function userForm( $name ) {
295 $htmlForm = HTMLForm::factory( 'ooui', [
296 'Target' => [
297 'type' => 'user',
298 'exists' => true,
299 'label' => $this->msg( 'emailusername' )->text(),
300 'id' => 'emailusertarget',
301 'autofocus' => true,
302 'value' => $name,
303 ]
304 ], $this->getContext() );
305
306 $htmlForm
307 ->setMethod( 'post' )
308 ->setSubmitCallback( [ $this, 'sendEmailForm' ] )
309 ->setFormIdentifier( 'userForm' )
310 ->setId( 'askusername' )
311 ->setWrapperLegendMsg( 'emailtarget' )
312 ->setSubmitTextMsg( 'emailusernamesubmit' )
313 ->show();
314 }
315
316 public function sendEmailForm() {
317 $out = $this->getOutput();
318
319 $ret = $this->mTargetObj;
320 if ( !$ret instanceof User ) {
321 if ( $this->mTarget != '' ) {
322 // Messages used here: notargettext, noemailtext, nowikiemailtext
323 $ret = ( $ret == 'notarget' ) ? 'emailnotarget' : ( $ret . 'text' );
324 return Status::newFatal( $ret );
325 }
326 return false;
327 }
328
329 $htmlForm = HTMLForm::factory( 'ooui', $this->getFormFields(), $this->getContext() );
330 // By now we are supposed to be sure that $this->mTarget is a user name
331 $htmlForm
332 ->addPreText( $this->msg( 'emailpagetext', $this->mTarget )->parse() )
333 ->setSubmitTextMsg( 'emailsend' )
334 ->setSubmitCallback( [ __CLASS__, 'submit' ] )
335 ->setFormIdentifier( 'sendEmailForm' )
336 ->setWrapperLegendMsg( 'email-legend' )
337 ->loadData();
338
339 if ( !Hooks::run( 'EmailUserForm', [ &$htmlForm ] ) ) {
340 return false;
341 }
342
343 $result = $htmlForm->show();
344
345 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
346 $out->setPageTitle( $this->msg( 'emailsent' ) );
347 $out->addWikiMsg( 'emailsenttext', $this->mTarget );
348 $out->returnToMain( false, $ret->getUserPage() );
349 }
350 return true;
351 }
352
353 /**
354 * Really send a mail. Permissions should have been checked using
355 * getPermissionsError(). It is probably also a good
356 * idea to check the edit token and ping limiter in advance.
357 *
358 * @param array $data
359 * @param IContextSource $context
360 * @return Status|bool
361 */
362 public static function submit( array $data, IContextSource $context ) {
363 $config = $context->getConfig();
364
365 $target = self::getTarget( $data['Target'], $context->getUser() );
366 if ( !$target instanceof User ) {
367 // Messages used here: notargettext, noemailtext, nowikiemailtext
368 return Status::newFatal( $target . 'text' );
369 }
370
371 $to = MailAddress::newFromUser( $target );
372 $from = MailAddress::newFromUser( $context->getUser() );
373 $subject = $data['Subject'];
374 $text = $data['Text'];
375
376 // Add a standard footer and trim up trailing newlines
377 $text = rtrim( $text ) . "\n\n-- \n";
378 $text .= $context->msg( 'emailuserfooter',
379 $from->name, $to->name )->inContentLanguage()->text();
380
381 if ( $config->get( 'EnableSpecialMute' ) ) {
382 $specialMutePage = SpecialPage::getTitleFor( 'Mute', $context->getUser()->getName() );
383 $text .= "\n" . $context->msg(
384 'specialmute-email-footer',
385 $specialMutePage->getCanonicalURL(),
386 $context->getUser()->getName()
387 )->inContentLanguage()->text();
388 }
389
390 // Check and increment the rate limits
391 if ( $context->getUser()->pingLimiter( 'emailuser' ) ) {
392 throw new ThrottledError();
393 }
394
395 $error = false;
396 if ( !Hooks::run( 'EmailUser', [ &$to, &$from, &$subject, &$text, &$error ] ) ) {
397 if ( $error instanceof Status ) {
398 return $error;
399 } elseif ( $error === false || $error === '' || $error === [] ) {
400 // Possibly to tell HTMLForm to pretend there was no submission?
401 return false;
402 } elseif ( $error === true ) {
403 // Hook sent the mail itself and indicates success?
404 return Status::newGood();
405 } elseif ( is_array( $error ) ) {
406 $status = Status::newGood();
407 foreach ( $error as $e ) {
408 $status->fatal( $e );
409 }
410 return $status;
411 } elseif ( $error instanceof MessageSpecifier ) {
412 return Status::newFatal( $error );
413 } else {
414 // Ugh. Either a raw HTML string, or something that's supposed
415 // to be treated like one.
416 $type = is_object( $error ) ? get_class( $error ) : gettype( $error );
417 wfDeprecated( "EmailUser hook returning a $type as \$error", '1.29' );
418 return Status::newFatal( new ApiRawMessage(
419 [ '$1', Message::rawParam( (string)$error ) ], 'hookaborted'
420 ) );
421 }
422 }
423
424 if ( $config->get( 'UserEmailUseReplyTo' ) ) {
425 /**
426 * Put the generic wiki autogenerated address in the From:
427 * header and reserve the user for Reply-To.
428 *
429 * This is a bit ugly, but will serve to differentiate
430 * wiki-borne mails from direct mails and protects against
431 * SPF and bounce problems with some mailers (see below).
432 */
433 $mailFrom = new MailAddress( $config->get( 'PasswordSender' ),
434 $context->msg( 'emailsender' )->inContentLanguage()->text() );
435 $replyTo = $from;
436 } else {
437 /**
438 * Put the sending user's e-mail address in the From: header.
439 *
440 * This is clean-looking and convenient, but has issues.
441 * One is that it doesn't as clearly differentiate the wiki mail
442 * from "directly" sent mails.
443 *
444 * Another is that some mailers (like sSMTP) will use the From
445 * address as the envelope sender as well. For open sites this
446 * can cause mails to be flunked for SPF violations (since the
447 * wiki server isn't an authorized sender for various users'
448 * domains) as well as creating a privacy issue as bounces
449 * containing the recipient's e-mail address may get sent to
450 * the sending user.
451 */
452 $mailFrom = $from;
453 $replyTo = null;
454 }
455
456 $status = UserMailer::send( $to, $mailFrom, $subject, $text, [
457 'replyTo' => $replyTo,
458 ] );
459
460 if ( !$status->isGood() ) {
461 return $status;
462 } else {
463 // if the user requested a copy of this mail, do this now,
464 // unless they are emailing themselves, in which case one
465 // copy of the message is sufficient.
466 if ( $data['CCMe'] && $to != $from ) {
467 $ccTo = $from;
468 $ccFrom = $from;
469 $ccSubject = $context->msg( 'emailccsubject' )->plaintextParams(
470 $target->getName(), $subject )->text();
471 $ccText = $text;
472
473 Hooks::run( 'EmailUserCC', [ &$ccTo, &$ccFrom, &$ccSubject, &$ccText ] );
474
475 if ( $config->get( 'UserEmailUseReplyTo' ) ) {
476 $mailFrom = new MailAddress(
477 $config->get( 'PasswordSender' ),
478 $context->msg( 'emailsender' )->inContentLanguage()->text()
479 );
480 $replyTo = $ccFrom;
481 } else {
482 $mailFrom = $ccFrom;
483 $replyTo = null;
484 }
485
486 $ccStatus = UserMailer::send(
487 $ccTo, $mailFrom, $ccSubject, $ccText, [
488 'replyTo' => $replyTo,
489 ] );
490 $status->merge( $ccStatus );
491 }
492
493 Hooks::run( 'EmailUserComplete', [ $to, $from, $subject, $text ] );
494
495 return $status;
496 }
497 }
498
499 /**
500 * Return an array of subpages beginning with $search that this special page will accept.
501 *
502 * @param string $search Prefix to search for
503 * @param int $limit Maximum number of results to return (usually 10)
504 * @param int $offset Number of results to skip (usually 0)
505 * @return string[] Matching subpages
506 */
507 public function prefixSearchSubpages( $search, $limit, $offset ) {
508 $user = User::newFromName( $search );
509 if ( !$user ) {
510 // No prefix suggestion for invalid user
511 return [];
512 }
513 // Autocomplete subpage as user list - public to allow caching
514 return UserNamePrefixSearch::search( 'public', $search, $limit, $offset );
515 }
516
517 protected function getGroupName() {
518 return 'users';
519 }
520
521 /**
522 * Builds an error message based on the block params
523 *
524 * @return ErrorPageError
525 */
526 private function getBlockedEmailError() {
527 $block = $this->getUser()->mBlock;
528 $params = $block->getBlockErrorParams( $this->getContext() );
529
530 $msg = $block->isSitewide() ? 'blockedtext' : 'blocked-email-user';
531 return new ErrorPageError( 'blockedtitle', $msg, $params );
532 }
533 }