Merge "Set visibility for class properties of DependencyWrapper"
[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 $loginForm->load();
87
88 $status = $loginForm->addNewaccountInternal();
89 $result = array();
90 if ( $status->isGood() ) {
91 // Success!
92 global $wgEmailAuthentication;
93 $user = $status->getValue();
94
95 if ( $params['language'] ) {
96 $user->setOption( 'language', $params['language'] );
97 }
98
99 if ( $params['mailpassword'] ) {
100 // If mailpassword was set, disable the password and send an email.
101 $user->setPassword( null );
102 $status->merge( $loginForm->mailPasswordInternal(
103 $user,
104 false,
105 'createaccount-title',
106 'createaccount-text'
107 ) );
108 } elseif ( $wgEmailAuthentication && Sanitizer::validateEmail( $user->getEmail() ) ) {
109 // Send out an email authentication message if needed
110 $status->merge( $user->sendConfirmationMail() );
111 }
112
113 // Save settings (including confirmation token)
114 $user->saveSettings();
115
116 wfRunHooks( 'AddNewAccount', array( $user, $params['mailpassword'] ) );
117
118 if ( $params['mailpassword'] ) {
119 $logAction = 'byemail';
120 } elseif ( $this->getUser()->isLoggedIn() ) {
121 $logAction = 'create2';
122 } else {
123 $logAction = 'create';
124 }
125 $user->addNewUserLogEntry( $logAction, (string)$params['reason'] );
126
127 // Add username, id, and token to result.
128 $result['username'] = $user->getName();
129 $result['userid'] = $user->getId();
130 $result['token'] = $user->getToken();
131 }
132
133 $apiResult = $this->getResult();
134
135 if ( $status->hasMessage( 'sessionfailure' ) || $status->hasMessage( 'nocookiesfornew' ) ) {
136 // Token was incorrect, so add it to result, but don't throw an exception
137 // since not having the correct token is part of the normal
138 // flow of events.
139 $result['token'] = LoginForm::getCreateaccountToken();
140 $result['result'] = 'needtoken';
141 } elseif ( !$status->isOK() ) {
142 // There was an error. Die now.
143 $this->dieStatus( $status );
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
184 return array(
185 'name' => array(
186 ApiBase::PARAM_TYPE => 'user',
187 ApiBase::PARAM_REQUIRED => true
188 ),
189 'password' => null,
190 'domain' => null,
191 'token' => null,
192 'email' => array(
193 ApiBase::PARAM_TYPE => 'string',
194 ApiBase::PARAM_REQUIRED => $wgEmailConfirmToEdit
195 ),
196 'realname' => null,
197 'mailpassword' => array(
198 ApiBase::PARAM_TYPE => 'boolean',
199 ApiBase::PARAM_DFLT => false
200 ),
201 'reason' => null,
202 'language' => null
203 );
204 }
205
206 public function getParamDescription() {
207 $p = $this->getModulePrefix();
208
209 return array(
210 'name' => 'Username',
211 'password' => "Password (ignored if {$p}mailpassword is set)",
212 'domain' => 'Domain for external authentication (optional)',
213 'token' => 'Account creation token obtained in first request',
214 'email' => 'Email address of user (optional)',
215 'realname' => 'Real name of user (optional)',
216 'mailpassword' => 'If set to any value, a random password will be emailed to the user',
217 'reason' => 'Optional reason for creating the account to be put in the logs',
218 'language'
219 => 'Language code to set as default for the user (optional, defaults to content language)'
220 );
221 }
222
223 public function getResultProperties() {
224 return array(
225 'createaccount' => array(
226 'result' => array(
227 ApiBase::PROP_TYPE => array(
228 'success',
229 'warning',
230 'needtoken'
231 )
232 ),
233 'username' => array(
234 ApiBase::PROP_TYPE => 'string',
235 ApiBase::PROP_NULLABLE => true
236 ),
237 'userid' => array(
238 ApiBase::PROP_TYPE => 'int',
239 ApiBase::PROP_NULLABLE => true
240 ),
241 'token' => array(
242 ApiBase::PROP_TYPE => 'string',
243 ApiBase::PROP_NULLABLE => true
244 ),
245 )
246 );
247 }
248
249 public function getPossibleErrors() {
250 // Note the following errors aren't possible and don't need to be listed:
251 // sessionfailure, nocookiesfornew, badretype
252 $localErrors = array(
253 'wrongpassword', // Actually caused by wrong domain field. Riddle me that...
254 'sorbs_create_account_reason',
255 'noname',
256 'userexists',
257 'password-name-match', // from User::getPasswordValidity
258 'password-login-forbidden', // from User::getPasswordValidity
259 'noemailtitle',
260 'invalidemailaddress',
261 'externaldberror',
262 'acct_creation_throttle_hit',
263 );
264
265 $errors = parent::getPossibleErrors();
266 // All local errors are from LoginForm, which means they're actually message keys.
267 foreach ( $localErrors as $error ) {
268 $errors[] = array(
269 'code' => $error,
270 'info' => wfMessage( $error )->inLanguage( 'en' )->useDatabase( false )->parse()
271 );
272 }
273
274 $errors[] = array(
275 'code' => 'permdenied-createaccount',
276 'info' => 'You do not have the right to create a new account'
277 );
278 $errors[] = array(
279 'code' => 'blocked',
280 'info' => 'You cannot create a new account because you are blocked'
281 );
282 $errors[] = array(
283 'code' => 'aborted',
284 'info' => 'Account creation aborted by hook (info may vary)'
285 );
286 $errors[] = array(
287 'code' => 'langinvalid',
288 'info' => 'Invalid language parameter'
289 );
290
291 // 'passwordtooshort' has parameters. :(
292 global $wgMinimalPasswordLength;
293 $errors[] = array(
294 'code' => 'passwordtooshort',
295 'info' => wfMessage( 'passwordtooshort', $wgMinimalPasswordLength )
296 ->inLanguage( 'en' )->useDatabase( false )->parse()
297 );
298
299 return $errors;
300 }
301
302 public function getExamples() {
303 return array(
304 'api.php?action=createaccount&name=testuser&password=test123',
305 'api.php?action=createaccount&name=testmailuser&mailpassword=true&reason=MyReason',
306 );
307 }
308
309 public function getHelpUrls() {
310 return 'https://www.mediawiki.org/wiki/API:Account_creation';
311 }
312 }