Set lang in api createaccount regardless of $wgLoginLanguageSelector
[lhc/web/wiklou.git] / includes / api / ApiCreateAccount.php
1 <?php
2 /**
3 * Created on August 7, 2012
4 *
5 * Copyright © 2012 Tyler Romeo <tylerromeo@gmail.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
21 *
22 * @file
23 */
24
25 /**
26 * Unit to authenticate account registration attempts to the current wiki.
27 *
28 * @ingroup API
29 */
30 class ApiCreateAccount extends ApiBase {
31 public function execute() {
32
33 // $loginForm->addNewaccountInternal will throw exceptions
34 // if wiki is read only (already handled by api), user is blocked or does not have rights.
35 // Use userCan in order to hit GlobalBlock checks (according to Special:userlogin)
36 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
37 if ( !$loginTitle->userCan( 'createaccount', $this->getUser() ) ) {
38 $this->dieUsage( 'You do not have the right to create a new account', 'permdenied-createaccount' );
39 }
40 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
41 $this->dieUsage( 'You cannot create a new account because you are blocked', 'blocked' );
42 }
43
44 $params = $this->extractRequestParams();
45
46 $result = array();
47
48 // Init session if necessary
49 if ( session_id() == '' ) {
50 wfSetupSession();
51 }
52
53 if( $params['mailpassword'] && !$params['email'] ) {
54 $this->dieUsageMsg( 'noemail' );
55 }
56
57 if ( $params['language'] && !Language::isSupportedLanguage( $params['language'] ) ) {
58 $this->dieUsage( 'Invalid language parameter', 'langinvalid' );
59 }
60
61 $context = new DerivativeContext( $this->getContext() );
62 $context->setRequest( new DerivativeRequest(
63 $this->getContext()->getRequest(),
64 array(
65 'type' => 'signup',
66 'uselang' => $params['language'],
67 'wpName' => $params['name'],
68 'wpPassword' => $params['password'],
69 'wpRetype' => $params['password'],
70 'wpDomain' => $params['domain'],
71 'wpEmail' => $params['email'],
72 'wpRealName' => $params['realname'],
73 'wpCreateaccountToken' => $params['token'],
74 'wpCreateaccount' => $params['mailpassword'] ? null : '1',
75 'wpCreateaccountMail' => $params['mailpassword'] ? '1' : null
76 )
77 ) );
78
79 $loginForm = new LoginForm();
80 $loginForm->setContext( $context );
81 $loginForm->load();
82
83 $status = $loginForm->addNewaccountInternal();
84 $result = array();
85 if( $status->isGood() ) {
86 // Success!
87 global $wgEmailAuthentication;
88 $user = $status->getValue();
89
90 if( $params['language'] ) {
91 $user->setOption( 'language', $params['language'] );
92 }
93
94 if( $params['mailpassword'] ) {
95 // If mailpassword was set, disable the password and send an email.
96 $user->setPassword( null );
97 $status->merge( $loginForm->mailPasswordInternal( $user, false, 'createaccount-title', 'createaccount-text' ) );
98 } elseif( $wgEmailAuthentication && Sanitizer::validateEmail( $user->getEmail() ) ) {
99 // Send out an email authentication message if needed
100 $status->merge( $user->sendConfirmationMail() );
101 }
102
103 // Save settings (including confirmation token)
104 $user->saveSettings();
105
106 wfRunHooks( 'AddNewAccount', array( $user, $params['mailpassword'] ) );
107
108 if ( $params['mailpassword'] ) {
109 $logAction = 'byemail';
110 } elseif ( $this->getUser()->isLoggedIn() ) {
111 $logAction = 'create2';
112 } else {
113 $logAction = 'create';
114 }
115 $user->addNewUserLogEntry( $logAction, (string)$params['reason'] );
116
117 // Add username, id, and token to result.
118 $result['username'] = $user->getName();
119 $result['userid'] = $user->getId();
120 $result['token'] = $user->getToken();
121 }
122
123 $apiResult = $this->getResult();
124
125 if( $status->hasMessage( 'sessionfailure' ) || $status->hasMessage( 'nocookiesfornew' ) ) {
126 // Token was incorrect, so add it to result, but don't throw an exception
127 // since not having the correct token is part of the normal
128 // flow of events.
129 $result['token'] = LoginForm::getCreateaccountToken();
130 $result['result'] = 'needtoken';
131 } elseif( !$status->isOK() ) {
132 // There was an error. Die now.
133 // Cannot use dieUsageMsg() directly because extensions
134 // might return custom error messages.
135 $errors = $status->getErrorsArray();
136 if( $errors[0] instanceof Message ) {
137 $code = 'aborted';
138 $desc = $errors[0];
139 } else {
140 $code = array_shift( $errors[0] );
141 $desc = wfMessage( $code, $errors[0] );
142 }
143 $this->dieUsage( $desc, $code );
144 } elseif( !$status->isGood() ) {
145 // Status is not good, but OK. This means warnings.
146 $result['result'] = 'warning';
147
148 // Add any warnings to the result
149 $warnings = $status->getErrorsByType( 'warning' );
150 if( $warnings ) {
151 foreach( $warnings as &$warning ) {
152 $apiResult->setIndexedTagName( $warning['params'], 'param' );
153 }
154 $apiResult->setIndexedTagName( $warnings, 'warning' );
155 $result['warnings'] = $warnings;
156 }
157 } else {
158 // Everything was fine.
159 $result['result'] = 'success';
160 }
161
162 $apiResult->addValue( null, 'createaccount', $result );
163 }
164
165 public function getDescription() {
166 return 'Create a new user account.';
167 }
168
169 public function mustBePosted() {
170 return true;
171 }
172
173 public function isReadMode() {
174 return false;
175 }
176
177 public function isWriteMode() {
178 return true;
179 }
180
181 public function getAllowedParams() {
182 global $wgEmailConfirmToEdit;
183 return array(
184 'name' => array(
185 ApiBase::PARAM_TYPE => 'user',
186 ApiBase::PARAM_REQUIRED => true
187 ),
188 'password' => null,
189 'domain' => null,
190 'token' => null,
191 'email' => array(
192 ApiBase::PARAM_TYPE => 'string',
193 ApiBase::PARAM_REQUIRED => $wgEmailConfirmToEdit
194 ),
195 'realname' => null,
196 'mailpassword' => array(
197 ApiBase::PARAM_TYPE => 'boolean',
198 ApiBase::PARAM_DFLT => false
199 ),
200 'reason' => null,
201 'language' => null
202 );
203 }
204
205 public function getParamDescription() {
206 $p = $this->getModulePrefix();
207 return array(
208 'name' => 'Username',
209 'password' => "Password (ignored if {$p}mailpassword is set)",
210 'domain' => 'Domain for external authentication (optional)',
211 'token' => 'Account creation token obtained in first request',
212 'email' => 'Email address of user (optional)',
213 'realname' => 'Real name of user (optional)',
214 'mailpassword' => 'If set to any value, a random password will be emailed to the user',
215 'reason' => 'Optional reason for creating the account to be put in the logs',
216 'language' => 'Language code to set as default for the user (optional, defaults to content language)'
217 );
218 }
219
220 public function getResultProperties() {
221 return array(
222 'createaccount' => array(
223 'result' => array(
224 ApiBase::PROP_TYPE => array(
225 'success',
226 'warning',
227 'needtoken'
228 )
229 ),
230 'username' => array(
231 ApiBase::PROP_TYPE => 'string',
232 ApiBase::PROP_NULLABLE => true
233 ),
234 'userid' => array(
235 ApiBase::PROP_TYPE => 'int',
236 ApiBase::PROP_NULLABLE => true
237 ),
238 'token' => array(
239 ApiBase::PROP_TYPE => 'string',
240 ApiBase::PROP_NULLABLE => true
241 ),
242 )
243 );
244 }
245
246 public function getPossibleErrors() {
247 // Note the following errors aren't possible and don't need to be listed:
248 // sessionfailure, nocookiesfornew, badretype
249 $localErrors = array(
250 'wrongpassword', // Actually caused by wrong domain field. Riddle me that...
251 'sorbs_create_account_reason',
252 'noname',
253 'userexists',
254 'password-name-match', // from User::getPasswordValidity
255 'password-login-forbidden', // from User::getPasswordValidity
256 'noemailtitle',
257 'invalidemailaddress',
258 'externaldberror',
259 'acct_creation_throttle_hit',
260 );
261
262 $errors = parent::getPossibleErrors();
263 // All local errors are from LoginForm, which means they're actually message keys.
264 foreach( $localErrors as $error ) {
265 $errors[] = array( 'code' => $error, 'info' => wfMessage( $error )->parse() );
266 }
267
268 $errors[] = array(
269 'code' => 'permdenied-createaccount',
270 'info' => 'You do not have the right to create a new account'
271 );
272 $errors[] = array(
273 'code' => 'blocked',
274 'info' => 'You cannot create a new account because you are blocked'
275 );
276 $errors[] = array(
277 'code' => 'aborted',
278 'info' => 'Account creation aborted by hook (info may vary)'
279 );
280 $errors[] = array(
281 'code' => 'langinvalid',
282 'info' => 'Invalid language parameter'
283 );
284
285 // 'passwordtooshort' has parameters. :(
286 global $wgMinimalPasswordLength;
287 $errors[] = array(
288 'code' => 'passwordtooshort',
289 'info' => wfMessage( 'passwordtooshort', $wgMinimalPasswordLength )->parse()
290 );
291 return $errors;
292 }
293
294 public function getExamples() {
295 return array(
296 'api.php?action=createaccount&name=testuser&password=test123',
297 'api.php?action=createaccount&name=testmailuser&mailpassword=true&reason=MyReason',
298 );
299 }
300
301 public function getHelpUrls() {
302 return 'https://www.mediawiki.org/wiki/API:Account_creation';
303 }
304 }