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