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