Make ApiCreateAccount return camelcase statuses
[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 // If we're in JSON callback mode, no tokens can be obtained
33 if ( !is_null( $this->getMain()->getRequest()->getVal( 'callback' ) ) ) {
34 $this->dieUsage( 'Cannot create account when using a callback', 'aborted' );
35 }
36
37 // $loginForm->addNewaccountInternal will throw exceptions
38 // if wiki is read only (already handled by api), user is blocked or does not have rights.
39 // Use userCan in order to hit GlobalBlock checks (according to Special:userlogin)
40 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
41 if ( !$loginTitle->userCan( 'createaccount', $this->getUser() ) ) {
42 $this->dieUsage(
43 'You do not have the right to create a new account',
44 'permdenied-createaccount'
45 );
46 }
47 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
48 $this->dieUsage( 'You cannot create a new account because you are blocked', 'blocked' );
49 }
50
51 $params = $this->extractRequestParams();
52
53 // Init session if necessary
54 if ( session_id() == '' ) {
55 wfSetupSession();
56 }
57
58 if ( $params['mailpassword'] && !$params['email'] ) {
59 $this->dieUsageMsg( 'noemail' );
60 }
61
62 if ( $params['language'] && !Language::isSupportedLanguage( $params['language'] ) ) {
63 $this->dieUsage( 'Invalid language parameter', 'langinvalid' );
64 }
65
66 $context = new DerivativeContext( $this->getContext() );
67 $context->setRequest( new DerivativeRequest(
68 $this->getContext()->getRequest(),
69 array(
70 'type' => 'signup',
71 'uselang' => $params['language'],
72 'wpName' => $params['name'],
73 'wpPassword' => $params['password'],
74 'wpRetype' => $params['password'],
75 'wpDomain' => $params['domain'],
76 'wpEmail' => $params['email'],
77 'wpRealName' => $params['realname'],
78 'wpCreateaccountToken' => $params['token'],
79 'wpCreateaccount' => $params['mailpassword'] ? null : '1',
80 'wpCreateaccountMail' => $params['mailpassword'] ? '1' : null
81 )
82 ) );
83
84 $loginForm = new LoginForm();
85 $loginForm->setContext( $context );
86 wfRunHooks( 'AddNewAccountApiForm', array( $this, $loginForm ) );
87 $loginForm->load();
88
89 $status = $loginForm->addNewaccountInternal();
90 $result = array();
91 if ( $status->isGood() ) {
92 // Success!
93 global $wgEmailAuthentication;
94 $user = $status->getValue();
95
96 if ( $params['language'] ) {
97 $user->setOption( 'language', $params['language'] );
98 }
99
100 if ( $params['mailpassword'] ) {
101 // If mailpassword was set, disable the password and send an email.
102 $user->setPassword( null );
103 $status->merge( $loginForm->mailPasswordInternal(
104 $user,
105 false,
106 'createaccount-title',
107 'createaccount-text'
108 ) );
109 } elseif ( $wgEmailAuthentication && Sanitizer::validateEmail( $user->getEmail() ) ) {
110 // Send out an email authentication message if needed
111 $status->merge( $user->sendConfirmationMail() );
112 }
113
114 // Save settings (including confirmation token)
115 $user->saveSettings();
116
117 wfRunHooks( 'AddNewAccount', array( $user, $params['mailpassword'] ) );
118
119 if ( $params['mailpassword'] ) {
120 $logAction = 'byemail';
121 } elseif ( $this->getUser()->isLoggedIn() ) {
122 $logAction = 'create2';
123 } else {
124 $logAction = 'create';
125 }
126 $user->addNewUserLogEntry( $logAction, (string)$params['reason'] );
127
128 // Add username, id, and token to result.
129 $result['username'] = $user->getName();
130 $result['userid'] = $user->getId();
131 $result['token'] = $user->getToken();
132 }
133
134 $apiResult = $this->getResult();
135
136 if ( $status->hasMessage( 'sessionfailure' ) || $status->hasMessage( 'nocookiesfornew' ) ) {
137 // Token was incorrect, so add it to result, but don't throw an exception
138 // since not having the correct token is part of the normal
139 // flow of events.
140 $result['token'] = LoginForm::getCreateaccountToken();
141 $result['result'] = 'NeedToken';
142 } elseif ( !$status->isOK() ) {
143 // There was an error. Die now.
144 $this->dieStatus( $status );
145 } elseif ( !$status->isGood() ) {
146 // Status is not good, but OK. This means warnings.
147 $result['result'] = 'Warning';
148
149 // Add any warnings to the result
150 $warnings = $status->getErrorsByType( 'warning' );
151 if ( $warnings ) {
152 foreach ( $warnings as &$warning ) {
153 $apiResult->setIndexedTagName( $warning['params'], 'param' );
154 }
155 $apiResult->setIndexedTagName( $warnings, 'warning' );
156 $result['warnings'] = $warnings;
157 }
158 } else {
159 // Everything was fine.
160 $result['result'] = 'Success';
161 }
162
163 // Give extensions a chance to modify the API result data
164 wfRunHooks( 'AddNewAccountApiResult', array( $this, $loginForm, &$result ) );
165
166 $apiResult->addValue( null, 'createaccount', $result );
167 }
168
169 public function getDescription() {
170 return 'Create a new user account.';
171 }
172
173 public function mustBePosted() {
174 return true;
175 }
176
177 public function isReadMode() {
178 return false;
179 }
180
181 public function isWriteMode() {
182 return true;
183 }
184
185 public function getAllowedParams() {
186 global $wgEmailConfirmToEdit;
187
188 return array(
189 'name' => array(
190 ApiBase::PARAM_TYPE => 'user',
191 ApiBase::PARAM_REQUIRED => true
192 ),
193 'password' => null,
194 'domain' => null,
195 'token' => null,
196 'email' => array(
197 ApiBase::PARAM_TYPE => 'string',
198 ApiBase::PARAM_REQUIRED => $wgEmailConfirmToEdit
199 ),
200 'realname' => null,
201 'mailpassword' => array(
202 ApiBase::PARAM_TYPE => 'boolean',
203 ApiBase::PARAM_DFLT => false
204 ),
205 'reason' => null,
206 'language' => null
207 );
208 }
209
210 public function getParamDescription() {
211 $p = $this->getModulePrefix();
212
213 return array(
214 'name' => 'Username',
215 'password' => "Password (ignored if {$p}mailpassword is set)",
216 'domain' => 'Domain for external authentication (optional)',
217 'token' => 'Account creation token obtained in first request',
218 'email' => 'Email address of user (optional)',
219 'realname' => 'Real name of user (optional)',
220 'mailpassword' => 'If set to any value, a random password will be emailed to the user',
221 'reason' => 'Optional reason for creating the account to be put in the logs',
222 'language'
223 => 'Language code to set as default for the user (optional, defaults to content language)'
224 );
225 }
226
227 public function getResultProperties() {
228 return array(
229 'createaccount' => array(
230 'result' => array(
231 ApiBase::PROP_TYPE => array(
232 'Success',
233 'Warning',
234 'NeedToken'
235 )
236 ),
237 'username' => array(
238 ApiBase::PROP_TYPE => 'string',
239 ApiBase::PROP_NULLABLE => true
240 ),
241 'userid' => array(
242 ApiBase::PROP_TYPE => 'int',
243 ApiBase::PROP_NULLABLE => true
244 ),
245 'token' => array(
246 ApiBase::PROP_TYPE => 'string',
247 ApiBase::PROP_NULLABLE => true
248 ),
249 )
250 );
251 }
252
253 public function getPossibleErrors() {
254 // Note the following errors aren't possible and don't need to be listed:
255 // sessionfailure, nocookiesfornew, badretype
256 $localErrors = array(
257 'wrongpassword', // Actually caused by wrong domain field. Riddle me that...
258 'sorbs_create_account_reason',
259 'noname',
260 'userexists',
261 'password-name-match', // from User::getPasswordValidity
262 'password-login-forbidden', // from User::getPasswordValidity
263 'noemailtitle',
264 'invalidemailaddress',
265 'externaldberror',
266 'acct_creation_throttle_hit',
267 );
268
269 $errors = parent::getPossibleErrors();
270 // All local errors are from LoginForm, which means they're actually message keys.
271 foreach ( $localErrors as $error ) {
272 $errors[] = array(
273 'code' => $error,
274 'info' => wfMessage( $error )->inLanguage( 'en' )->useDatabase( false )->parse()
275 );
276 }
277
278 $errors[] = array(
279 'code' => 'permdenied-createaccount',
280 'info' => 'You do not have the right to create a new account'
281 );
282 $errors[] = array(
283 'code' => 'blocked',
284 'info' => 'You cannot create a new account because you are blocked'
285 );
286 $errors[] = array(
287 'code' => 'aborted',
288 'info' => 'Account creation aborted by hook (info may vary)'
289 );
290 $errors[] = array(
291 'code' => 'langinvalid',
292 'info' => 'Invalid language parameter'
293 );
294
295 // 'passwordtooshort' has parameters. :(
296 global $wgMinimalPasswordLength;
297 $errors[] = array(
298 'code' => 'passwordtooshort',
299 'info' => wfMessage( 'passwordtooshort', $wgMinimalPasswordLength )
300 ->inLanguage( 'en' )->useDatabase( false )->parse()
301 );
302
303 return $errors;
304 }
305
306 public function getExamples() {
307 return array(
308 'api.php?action=createaccount&name=testuser&password=test123',
309 'api.php?action=createaccount&name=testmailuser&mailpassword=true&reason=MyReason',
310 );
311 }
312
313 public function getHelpUrls() {
314 return 'https://www.mediawiki.org/wiki/API:Account_creation';
315 }
316 }