Merge "Improve docs for Title::getInternalURL/getCanonicalURL"
[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|null $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 = null ) {
173 if ( $sender === null ) {
174 wfDeprecated( __METHOD__ . ' without specifying the sending user', '1.30' );
175 }
176
177 if ( $target == '' ) {
178 wfDebug( "Target is empty.\n" );
179
180 return 'notarget';
181 }
182
183 $nu = User::newFromName( $target );
184 $error = self::validateTarget( $nu, $sender );
185
186 return $error ?: $nu;
187 }
188
189 /**
190 * Validate target User
191 *
192 * @param User $target Target user
193 * @param User|null $sender User sending the email
194 * @return string Error message or empty string if valid.
195 * @since 1.30
196 */
197 public static function validateTarget( $target, User $sender = null ) {
198 if ( $sender === null ) {
199 wfDeprecated( __METHOD__ . ' without specifying the sending user', '1.30' );
200 }
201
202 if ( !$target instanceof User || !$target->getId() ) {
203 wfDebug( "Target is invalid user.\n" );
204
205 return 'notarget';
206 }
207
208 if ( !$target->isEmailConfirmed() ) {
209 wfDebug( "User has no valid email.\n" );
210
211 return 'noemail';
212 }
213
214 if ( !$target->canReceiveEmail() ) {
215 wfDebug( "User does not allow user emails.\n" );
216
217 return 'nowikiemail';
218 }
219
220 if ( $sender !== null && !$target->getOption( 'email-allow-new-users' ) &&
221 $sender->isNewbie()
222 ) {
223 wfDebug( "User does not allow user emails from new users.\n" );
224
225 return 'nowikiemail';
226 }
227
228 if ( $sender !== null ) {
229 $blacklist = $target->getOption( 'email-blacklist', '' );
230 if ( $blacklist ) {
231 $blacklist = MultiUsernameFilter::splitIds( $blacklist );
232 $lookup = CentralIdLookup::factory();
233 $senderId = $lookup->centralIdFromLocalUser( $sender );
234 if ( $senderId !== 0 && in_array( $senderId, $blacklist ) ) {
235 wfDebug( "User does not allow user emails from this user.\n" );
236
237 return 'nowikiemail';
238 }
239 }
240 }
241
242 return '';
243 }
244
245 /**
246 * Check whether a user is allowed to send email
247 *
248 * @param User $user
249 * @param string $editToken Edit token
250 * @param Config|null $config optional for backwards compatibility
251 * @return null|string|array Null on success, string on error, or array on
252 * hook error
253 */
254 public static function getPermissionsError( $user, $editToken, Config $config = null ) {
255 if ( $config === null ) {
256 wfDebug( __METHOD__ . ' called without a Config instance passed to it' );
257 $config = MediaWikiServices::getInstance()->getMainConfig();
258 }
259 if ( !$config->get( 'EnableEmail' ) || !$config->get( 'EnableUserEmail' ) ) {
260 return 'usermaildisabled';
261 }
262
263 // Run this before $user->isAllowed, to show appropriate message to anons (T160309)
264 if ( !$user->isEmailConfirmed() ) {
265 return 'mailnologin';
266 }
267
268 if ( !$user->isAllowed( 'sendemail' ) ) {
269 return 'badaccess';
270 }
271
272 if ( $user->isBlockedFromEmailuser() ) {
273 wfDebug( "User is blocked from sending e-mail.\n" );
274
275 return "blockedemailuser";
276 }
277
278 // Check the ping limiter without incrementing it - we'll check it
279 // again later and increment it on a successful send
280 if ( $user->pingLimiter( 'emailuser', 0 ) ) {
281 wfDebug( "Ping limiter triggered.\n" );
282
283 return 'actionthrottledtext';
284 }
285
286 $hookErr = false;
287
288 Hooks::run( 'UserCanSendEmail', [ &$user, &$hookErr ] );
289 Hooks::run( 'EmailUserPermissionsErrors', [ $user, $editToken, &$hookErr ] );
290
291 if ( $hookErr ) {
292 return $hookErr;
293 }
294
295 return null;
296 }
297
298 /**
299 * Form to ask for target user name.
300 *
301 * @param string $name User name submitted.
302 */
303 protected function userForm( $name ) {
304 $htmlForm = HTMLForm::factory( 'ooui', [
305 'Target' => [
306 'type' => 'user',
307 'exists' => true,
308 'label' => $this->msg( 'emailusername' )->text(),
309 'id' => 'emailusertarget',
310 'autofocus' => true,
311 'value' => $name,
312 ]
313 ], $this->getContext() );
314
315 $htmlForm
316 ->setMethod( 'post' )
317 ->setSubmitCallback( [ $this, 'sendEmailForm' ] )
318 ->setFormIdentifier( 'userForm' )
319 ->setId( 'askusername' )
320 ->setWrapperLegendMsg( 'emailtarget' )
321 ->setSubmitTextMsg( 'emailusernamesubmit' )
322 ->show();
323 }
324
325 public function sendEmailForm() {
326 $out = $this->getOutput();
327
328 $ret = $this->mTargetObj;
329 if ( !$ret instanceof User ) {
330 if ( $this->mTarget != '' ) {
331 // Messages used here: notargettext, noemailtext, nowikiemailtext
332 $ret = ( $ret == 'notarget' ) ? 'emailnotarget' : ( $ret . 'text' );
333 return Status::newFatal( $ret );
334 }
335 return false;
336 }
337
338 $htmlForm = HTMLForm::factory( 'ooui', $this->getFormFields(), $this->getContext() );
339 // By now we are supposed to be sure that $this->mTarget is a user name
340 $htmlForm
341 ->addPreText( $this->msg( 'emailpagetext', $this->mTarget )->parse() )
342 ->setSubmitTextMsg( 'emailsend' )
343 ->setSubmitCallback( [ __CLASS__, 'submit' ] )
344 ->setFormIdentifier( 'sendEmailForm' )
345 ->setWrapperLegendMsg( 'email-legend' )
346 ->loadData();
347
348 if ( !Hooks::run( 'EmailUserForm', [ &$htmlForm ] ) ) {
349 return false;
350 }
351
352 $result = $htmlForm->show();
353
354 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
355 $out->setPageTitle( $this->msg( 'emailsent' ) );
356 $out->addWikiMsg( 'emailsenttext', $this->mTarget );
357 $out->returnToMain( false, $ret->getUserPage() );
358 }
359 return true;
360 }
361
362 /**
363 * Really send a mail. Permissions should have been checked using
364 * getPermissionsError(). It is probably also a good
365 * idea to check the edit token and ping limiter in advance.
366 *
367 * @param array $data
368 * @param IContextSource $context
369 * @return Status|bool
370 */
371 public static function submit( array $data, IContextSource $context ) {
372 $config = $context->getConfig();
373
374 $target = self::getTarget( $data['Target'], $context->getUser() );
375 if ( !$target instanceof User ) {
376 // Messages used here: notargettext, noemailtext, nowikiemailtext
377 return Status::newFatal( $target . 'text' );
378 }
379
380 $to = MailAddress::newFromUser( $target );
381 $from = MailAddress::newFromUser( $context->getUser() );
382 $subject = $data['Subject'];
383 $text = $data['Text'];
384
385 // Add a standard footer and trim up trailing newlines
386 $text = rtrim( $text ) . "\n\n-- \n";
387 $text .= $context->msg( 'emailuserfooter',
388 $from->name, $to->name )->inContentLanguage()->text();
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 }