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