80ef4b180d3cf4cd8b6d29d5b99f629387dae93c
[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
24 /**
25 * A special page that allows users to send e-mails to other users
26 *
27 * @ingroup SpecialPage
28 */
29 class SpecialEmailUser extends UnlistedSpecialPage {
30 protected $mTarget;
31
32 /**
33 * @var User|string $mTargetObj
34 */
35 protected $mTargetObj;
36
37 public function __construct() {
38 parent::__construct( 'Emailuser' );
39 }
40
41 public function doesWrites() {
42 return true;
43 }
44
45 public function getDescription() {
46 $target = self::getTarget( $this->mTarget );
47 if ( !$target instanceof User ) {
48 return $this->msg( 'emailuser-title-notarget' )->text();
49 }
50
51 return $this->msg( 'emailuser-title-target', $target->getName() )->text();
52 }
53
54 protected function getFormFields() {
55 return [
56 'From' => [
57 'type' => 'info',
58 'raw' => 1,
59 'default' => Linker::link(
60 $this->getUser()->getUserPage(),
61 htmlspecialchars( $this->getUser()->getName() )
62 ),
63 'label-message' => 'emailfrom',
64 'id' => 'mw-emailuser-sender',
65 ],
66 'To' => [
67 'type' => 'info',
68 'raw' => 1,
69 'default' => Linker::link(
70 $this->mTargetObj->getUserPage(),
71 htmlspecialchars( $this->mTargetObj->getName() )
72 ),
73 'label-message' => 'emailto',
74 'id' => 'mw-emailuser-recipient',
75 ],
76 'Target' => [
77 'type' => 'hidden',
78 'default' => $this->mTargetObj->getName(),
79 ],
80 'Subject' => [
81 'type' => 'text',
82 'default' => $this->msg( 'defemailsubject',
83 $this->getUser()->getName() )->inContentLanguage()->text(),
84 'label-message' => 'emailsubject',
85 'maxlength' => 200,
86 'size' => 60,
87 'required' => true,
88 ],
89 'Text' => [
90 'type' => 'textarea',
91 'rows' => 20,
92 'cols' => 80,
93 'label-message' => 'emailmessage',
94 'required' => true,
95 ],
96 'CCMe' => [
97 'type' => 'check',
98 'label-message' => 'emailccme',
99 'default' => $this->getUser()->getBoolOption( 'ccmeonemails' ),
100 ],
101 ];
102 }
103
104 public function execute( $par ) {
105 $out = $this->getOutput();
106 $out->addModuleStyles( 'mediawiki.special' );
107
108 $this->mTarget = is_null( $par )
109 ? $this->getRequest()->getVal( 'wpTarget', $this->getRequest()->getVal( 'target', '' ) )
110 : $par;
111
112 // This needs to be below assignment of $this->mTarget because
113 // getDescription() needs it to determine the correct page title.
114 $this->setHeaders();
115 $this->outputHeader();
116
117 // error out if sending user cannot do this
118 $error = self::getPermissionsError(
119 $this->getUser(),
120 $this->getRequest()->getVal( 'wpEditToken' ),
121 $this->getConfig()
122 );
123
124 switch ( $error ) {
125 case null:
126 # Wahey!
127 break;
128 case 'badaccess':
129 throw new PermissionsError( 'sendemail' );
130 case 'blockedemailuser':
131 throw new UserBlockedError( $this->getUser()->mBlock );
132 case 'actionthrottledtext':
133 throw new ThrottledError;
134 case 'mailnologin':
135 case 'usermaildisabled':
136 throw new ErrorPageError( $error, "{$error}text" );
137 default:
138 # It's a hook error
139 list( $title, $msg, $params ) = $error;
140 throw new ErrorPageError( $title, $msg, $params );
141 }
142 // Got a valid target user name? Else ask for one.
143 $ret = self::getTarget( $this->mTarget );
144 if ( !$ret instanceof User ) {
145 if ( $this->mTarget != '' ) {
146 // Messages used here: notargettext, noemailtext, nowikiemailtext
147 $ret = ( $ret == 'notarget' ) ? 'emailnotarget' : ( $ret . 'text' );
148 $out->wrapWikiMsg( "<p class='error'>$1</p>", $ret );
149 }
150 $out->addHTML( $this->userForm( $this->mTarget ) );
151
152 return;
153 }
154
155 $this->mTargetObj = $ret;
156
157 $context = new DerivativeContext( $this->getContext() );
158 $context->setTitle( $this->getPageTitle() ); // Remove subpage
159 $form = new HTMLForm( $this->getFormFields(), $context );
160 // By now we are supposed to be sure that $this->mTarget is a user name
161 $form->addPreText( $this->msg( 'emailpagetext', $this->mTarget )->parse() );
162 $form->setSubmitTextMsg( 'emailsend' );
163 $form->setSubmitCallback( [ __CLASS__, 'uiSubmit' ] );
164 $form->setWrapperLegendMsg( 'email-legend' );
165 $form->loadData();
166
167 if ( !Hooks::run( 'EmailUserForm', [ &$form ] ) ) {
168 return;
169 }
170
171 $result = $form->show();
172
173 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
174 $out->setPageTitle( $this->msg( 'emailsent' ) );
175 $out->addWikiMsg( 'emailsenttext', $this->mTarget );
176 $out->returnToMain( false, $this->mTargetObj->getUserPage() );
177 }
178 }
179
180 /**
181 * Validate target User
182 *
183 * @param string $target Target user name
184 * @return User User object on success or a string on error
185 */
186 public static function getTarget( $target ) {
187 if ( $target == '' ) {
188 wfDebug( "Target is empty.\n" );
189
190 return 'notarget';
191 }
192
193 $nu = User::newFromName( $target );
194 if ( !$nu instanceof User || !$nu->getId() ) {
195 wfDebug( "Target is invalid user.\n" );
196
197 return 'notarget';
198 } elseif ( !$nu->isEmailConfirmed() ) {
199 wfDebug( "User has no valid email.\n" );
200
201 return 'noemail';
202 } elseif ( !$nu->canReceiveEmail() ) {
203 wfDebug( "User does not allow user emails.\n" );
204
205 return 'nowikiemail';
206 }
207
208 return $nu;
209 }
210
211 /**
212 * Check whether a user is allowed to send email
213 *
214 * @param User $user
215 * @param string $editToken Edit token
216 * @param Config $config optional for backwards compatibility
217 * @return string|null Null on success or string on error
218 */
219 public static function getPermissionsError( $user, $editToken, Config $config = null ) {
220 if ( $config === null ) {
221 wfDebug( __METHOD__ . ' called without a Config instance passed to it' );
222 $config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
223 }
224 if ( !$config->get( 'EnableEmail' ) || !$config->get( 'EnableUserEmail' ) ) {
225 return 'usermaildisabled';
226 }
227
228 if ( !$user->isAllowed( 'sendemail' ) ) {
229 return 'badaccess';
230 }
231
232 if ( !$user->isEmailConfirmed() ) {
233 return 'mailnologin';
234 }
235
236 if ( $user->isBlockedFromEmailuser() ) {
237 wfDebug( "User is blocked from sending e-mail.\n" );
238
239 return "blockedemailuser";
240 }
241
242 if ( $user->pingLimiter( 'emailuser' ) ) {
243 wfDebug( "Ping limiter triggered.\n" );
244
245 return 'actionthrottledtext';
246 }
247
248 $hookErr = false;
249
250 Hooks::run( 'UserCanSendEmail', [ &$user, &$hookErr ] );
251 Hooks::run( 'EmailUserPermissionsErrors', [ $user, $editToken, &$hookErr ] );
252
253 if ( $hookErr ) {
254 return $hookErr;
255 }
256
257 return null;
258 }
259
260 /**
261 * Form to ask for target user name.
262 *
263 * @param string $name User name submitted.
264 * @return string Form asking for user name.
265 */
266 protected function userForm( $name ) {
267 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
268 $string = Xml::openElement(
269 'form',
270 [ 'method' => 'get', 'action' => wfScript(), 'id' => 'askusername' ]
271 ) .
272 Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
273 Xml::openElement( 'fieldset' ) .
274 Html::rawElement( 'legend', null, $this->msg( 'emailtarget' )->parse() ) .
275 Xml::inputLabel(
276 $this->msg( 'emailusername' )->text(),
277 'target',
278 'emailusertarget',
279 30,
280 $name,
281 [
282 'class' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
283 'autofocus' => '',
284 ]
285 ) .
286 ' ' .
287 Xml::submitButton( $this->msg( 'emailusernamesubmit' )->text() ) .
288 Xml::closeElement( 'fieldset' ) .
289 Xml::closeElement( 'form' ) . "\n";
290
291 return $string;
292 }
293
294 /**
295 * Submit callback for an HTMLForm object, will simply call submit().
296 *
297 * @since 1.20
298 * @param array $data
299 * @param HTMLForm $form
300 * @return Status|string|bool
301 */
302 public static function uiSubmit( array $data, HTMLForm $form ) {
303 return self::submit( $data, $form->getContext() );
304 }
305
306 /**
307 * Really send a mail. Permissions should have been checked using
308 * getPermissionsError(). It is probably also a good
309 * idea to check the edit token and ping limiter in advance.
310 *
311 * @param array $data
312 * @param IContextSource $context
313 * @return Status|string|bool Status object, or potentially a String on error
314 * or maybe even true on success if anything uses the EmailUser hook.
315 */
316 public static function submit( array $data, IContextSource $context ) {
317 $config = $context->getConfig();
318
319 $target = self::getTarget( $data['Target'] );
320 if ( !$target instanceof User ) {
321 // Messages used here: notargettext, noemailtext, nowikiemailtext
322 return $context->msg( $target . 'text' )->parseAsBlock();
323 }
324
325 $to = MailAddress::newFromUser( $target );
326 $from = MailAddress::newFromUser( $context->getUser() );
327 $subject = $data['Subject'];
328 $text = $data['Text'];
329
330 // Add a standard footer and trim up trailing newlines
331 $text = rtrim( $text ) . "\n\n-- \n";
332 $text .= $context->msg( 'emailuserfooter',
333 $from->name, $to->name )->inContentLanguage()->text();
334
335 $error = '';
336 if ( !Hooks::run( 'EmailUser', [ &$to, &$from, &$subject, &$text, &$error ] ) ) {
337 return $error;
338 }
339
340 if ( $config->get( 'UserEmailUseReplyTo' ) ) {
341 /**
342 * Put the generic wiki autogenerated address in the From:
343 * header and reserve the user for Reply-To.
344 *
345 * This is a bit ugly, but will serve to differentiate
346 * wiki-borne mails from direct mails and protects against
347 * SPF and bounce problems with some mailers (see below).
348 */
349 $mailFrom = new MailAddress( $config->get( 'PasswordSender' ),
350 wfMessage( 'emailsender' )->inContentLanguage()->text() );
351 $replyTo = $from;
352 } else {
353 /**
354 * Put the sending user's e-mail address in the From: header.
355 *
356 * This is clean-looking and convenient, but has issues.
357 * One is that it doesn't as clearly differentiate the wiki mail
358 * from "directly" sent mails.
359 *
360 * Another is that some mailers (like sSMTP) will use the From
361 * address as the envelope sender as well. For open sites this
362 * can cause mails to be flunked for SPF violations (since the
363 * wiki server isn't an authorized sender for various users'
364 * domains) as well as creating a privacy issue as bounces
365 * containing the recipient's e-mail address may get sent to
366 * the sending user.
367 */
368 $mailFrom = $from;
369 $replyTo = null;
370 }
371
372 $status = UserMailer::send( $to, $mailFrom, $subject, $text, [
373 'replyTo' => $replyTo,
374 ] );
375
376 if ( !$status->isGood() ) {
377 return $status;
378 } else {
379 // if the user requested a copy of this mail, do this now,
380 // unless they are emailing themselves, in which case one
381 // copy of the message is sufficient.
382 if ( $data['CCMe'] && $to != $from ) {
383 $cc_subject = $context->msg( 'emailccsubject' )->rawParams(
384 $target->getName(), $subject )->text();
385
386 // target and sender are equal, because this is the CC for the sender
387 Hooks::run( 'EmailUserCC', [ &$from, &$from, &$cc_subject, &$text ] );
388
389 $ccStatus = UserMailer::send( $from, $from, $cc_subject, $text );
390 $status->merge( $ccStatus );
391 }
392
393 Hooks::run( 'EmailUserComplete', [ $to, $from, $subject, $text ] );
394
395 return $status;
396 }
397 }
398
399 /**
400 * Return an array of subpages beginning with $search that this special page will accept.
401 *
402 * @param string $search Prefix to search for
403 * @param int $limit Maximum number of results to return (usually 10)
404 * @param int $offset Number of results to skip (usually 0)
405 * @return string[] Matching subpages
406 */
407 public function prefixSearchSubpages( $search, $limit, $offset ) {
408 $user = User::newFromName( $search );
409 if ( !$user ) {
410 // No prefix suggestion for invalid user
411 return [];
412 }
413 // Autocomplete subpage as user list - public to allow caching
414 return UserNamePrefixSearch::search( 'public', $search, $limit, $offset );
415 }
416
417 protected function getGroupName() {
418 return 'users';
419 }
420 }