3 * Created on August 7, 2012
5 * Copyright © 2012 Tyler Romeo <tylerromeo@gmail.com>
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.
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.
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
26 * Unit to authenticate account registration attempts to the current wiki.
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' );
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() ) ) {
43 'You do not have the right to create a new account',
44 'permdenied-createaccount'
47 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
48 $this->dieUsage( 'You cannot create a new account because you are blocked', 'blocked' );
51 $params = $this->extractRequestParams();
53 // Init session if necessary
54 if ( session_id() == '' ) {
58 if ( $params['mailpassword'] && !$params['email'] ) {
59 $this->dieUsageMsg( 'noemail' );
62 if ( $params['language'] && !Language
::isSupportedLanguage( $params['language'] ) ) {
63 $this->dieUsage( 'Invalid language parameter', 'langinvalid' );
66 $context = new DerivativeContext( $this->getContext() );
67 $context->setRequest( new DerivativeRequest(
68 $this->getContext()->getRequest(),
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
84 $loginForm = new LoginForm();
85 $loginForm->setContext( $context );
86 wfRunHooks( 'AddNewAccountApiForm', array( $this, $loginForm ) );
89 $status = $loginForm->addNewaccountInternal();
91 if ( $status->isGood() ) {
93 global $wgEmailAuthentication;
94 $user = $status->getValue();
96 if ( $params['language'] ) {
97 $user->setOption( 'language', $params['language'] );
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(
106 'createaccount-title',
109 } elseif ( $wgEmailAuthentication && Sanitizer
::validateEmail( $user->getEmail() ) ) {
110 // Send out an email authentication message if needed
111 $status->merge( $user->sendConfirmationMail() );
114 // Save settings (including confirmation token)
115 $user->saveSettings();
117 wfRunHooks( 'AddNewAccount', array( $user, $params['mailpassword'] ) );
119 if ( $params['mailpassword'] ) {
120 $logAction = 'byemail';
121 } elseif ( $this->getUser()->isLoggedIn() ) {
122 $logAction = 'create2';
124 $logAction = 'create';
126 $user->addNewUserLogEntry( $logAction, (string)$params['reason'] );
128 // Add username, id, and token to result.
129 $result['username'] = $user->getName();
130 $result['userid'] = $user->getId();
131 $result['token'] = $user->getToken();
134 $apiResult = $this->getResult();
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
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';
149 // Add any warnings to the result
150 $warnings = $status->getErrorsByType( 'warning' );
152 foreach ( $warnings as &$warning ) {
153 $apiResult->setIndexedTagName( $warning['params'], 'param' );
155 $apiResult->setIndexedTagName( $warnings, 'warning' );
156 $result['warnings'] = $warnings;
159 // Everything was fine.
160 $result['result'] = 'Success';
163 // Give extensions a chance to modify the API result data
164 wfRunHooks( 'AddNewAccountApiResult', array( $this, $loginForm, &$result ) );
166 $apiResult->addValue( null, 'createaccount', $result );
169 public function getDescription() {
170 return 'Create a new user account.';
173 public function mustBePosted() {
177 public function isReadMode() {
181 public function isWriteMode() {
185 public function getAllowedParams() {
186 global $wgEmailConfirmToEdit;
190 ApiBase
::PARAM_TYPE
=> 'user',
191 ApiBase
::PARAM_REQUIRED
=> true
197 ApiBase
::PARAM_TYPE
=> 'string',
198 ApiBase
::PARAM_REQUIRED
=> $wgEmailConfirmToEdit
201 'mailpassword' => array(
202 ApiBase
::PARAM_TYPE
=> 'boolean',
203 ApiBase
::PARAM_DFLT
=> false
210 public function getParamDescription() {
211 $p = $this->getModulePrefix();
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',
223 => 'Language code to set as default for the user (optional, defaults to content language)'
227 public function getResultProperties() {
229 'createaccount' => array(
231 ApiBase
::PROP_TYPE
=> array(
238 ApiBase
::PROP_TYPE
=> 'string',
239 ApiBase
::PROP_NULLABLE
=> true
242 ApiBase
::PROP_TYPE
=> 'int',
243 ApiBase
::PROP_NULLABLE
=> true
246 ApiBase
::PROP_TYPE
=> 'string',
247 ApiBase
::PROP_NULLABLE
=> true
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',
261 'password-name-match', // from User::getPasswordValidity
262 'password-login-forbidden', // from User::getPasswordValidity
264 'invalidemailaddress',
266 'acct_creation_throttle_hit',
269 $errors = parent
::getPossibleErrors();
270 // All local errors are from LoginForm, which means they're actually message keys.
271 foreach ( $localErrors as $error ) {
274 'info' => wfMessage( $error )->inLanguage( 'en' )->useDatabase( false )->parse()
279 'code' => 'permdenied-createaccount',
280 'info' => 'You do not have the right to create a new account'
284 'info' => 'You cannot create a new account because you are blocked'
288 'info' => 'Account creation aborted by hook (info may vary)'
291 'code' => 'langinvalid',
292 'info' => 'Invalid language parameter'
295 // 'passwordtooshort' has parameters. :(
296 global $wgMinimalPasswordLength;
298 'code' => 'passwordtooshort',
299 'info' => wfMessage( 'passwordtooshort', $wgMinimalPasswordLength )
300 ->inLanguage( 'en' )->useDatabase( false )->parse()
306 public function getExamples() {
308 'api.php?action=createaccount&name=testuser&password=test123',
309 'api.php?action=createaccount&name=testmailuser&mailpassword=true&reason=MyReason',
313 public function getHelpUrls() {
314 return 'https://www.mediawiki.org/wiki/API:Account_creation';