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() {
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' );
40 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
41 $this->dieUsage( 'You cannot create a new account because you are blocked', 'blocked' );
44 $params = $this->extractRequestParams();
48 // Init session if necessary
49 if ( session_id() == '' ) {
53 if( $params['mailpassword'] && !$params['email'] ) {
54 $this->dieUsageMsg( 'noemail' );
57 if ( $params['language'] && !Language
::isSupportedLanguage( $params['language'] ) ) {
58 $this->dieUsage( 'Invalid language parameter', 'langinvalid' );
61 $context = new DerivativeContext( $this->getContext() );
62 $context->setRequest( new DerivativeRequest(
63 $this->getContext()->getRequest(),
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
79 $loginForm = new LoginForm();
80 $loginForm->setContext( $context );
83 $status = $loginForm->addNewaccountInternal();
85 if( $status->isGood() ) {
87 global $wgEmailAuthentication;
88 $user = $status->getValue();
90 if( $params['language'] ) {
91 $user->setOption( 'language', $params['language'] );
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() );
103 // Save settings (including confirmation token)
104 $user->saveSettings();
106 wfRunHooks( 'AddNewAccount', array( $user, $params['mailpassword'] ) );
108 if ( $params['mailpassword'] ) {
109 $logAction = 'byemail';
110 } elseif ( $this->getUser()->isLoggedIn() ) {
111 $logAction = 'create2';
113 $logAction = 'create';
115 $user->addNewUserLogEntry( $logAction, (string)$params['reason'] );
117 // Add username, id, and token to result.
118 $result['username'] = $user->getName();
119 $result['userid'] = $user->getId();
120 $result['token'] = $user->getToken();
123 $apiResult = $this->getResult();
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
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
) {
140 $code = array_shift( $errors[0] );
141 $desc = wfMessage( $code, $errors[0] );
143 $this->dieUsage( $desc, $code );
144 } elseif( !$status->isGood() ) {
145 // Status is not good, but OK. This means warnings.
146 $result['result'] = 'warning';
148 // Add any warnings to the result
149 $warnings = $status->getErrorsByType( 'warning' );
151 foreach( $warnings as &$warning ) {
152 $apiResult->setIndexedTagName( $warning['params'], 'param' );
154 $apiResult->setIndexedTagName( $warnings, 'warning' );
155 $result['warnings'] = $warnings;
158 // Everything was fine.
159 $result['result'] = 'success';
162 $apiResult->addValue( null, 'createaccount', $result );
165 public function getDescription() {
166 return 'Create a new user account.';
169 public function mustBePosted() {
173 public function isReadMode() {
177 public function isWriteMode() {
181 public function getAllowedParams() {
182 global $wgEmailConfirmToEdit;
185 ApiBase
::PARAM_TYPE
=> 'user',
186 ApiBase
::PARAM_REQUIRED
=> true
192 ApiBase
::PARAM_TYPE
=> 'string',
193 ApiBase
::PARAM_REQUIRED
=> $wgEmailConfirmToEdit
196 'mailpassword' => array(
197 ApiBase
::PARAM_TYPE
=> 'boolean',
198 ApiBase
::PARAM_DFLT
=> false
205 public function getParamDescription() {
206 $p = $this->getModulePrefix();
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)'
220 public function getResultProperties() {
222 'createaccount' => array(
224 ApiBase
::PROP_TYPE
=> array(
231 ApiBase
::PROP_TYPE
=> 'string',
232 ApiBase
::PROP_NULLABLE
=> true
235 ApiBase
::PROP_TYPE
=> 'int',
236 ApiBase
::PROP_NULLABLE
=> true
239 ApiBase
::PROP_TYPE
=> 'string',
240 ApiBase
::PROP_NULLABLE
=> true
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',
254 'password-name-match', // from User::getPasswordValidity
255 'password-login-forbidden', // from User::getPasswordValidity
257 'invalidemailaddress',
259 'acct_creation_throttle_hit',
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() );
269 'code' => 'permdenied-createaccount',
270 'info' => 'You do not have the right to create a new account'
274 'info' => 'You cannot create a new account because you are blocked'
278 'info' => 'Account creation aborted by hook (info may vary)'
281 'code' => 'langinvalid',
282 'info' => 'Invalid language parameter'
285 // 'passwordtooshort' has parameters. :(
286 global $wgMinimalPasswordLength;
288 'code' => 'passwordtooshort',
289 'info' => wfMessage( 'passwordtooshort', $wgMinimalPasswordLength )->parse()
294 public function getExamples() {
296 'api.php?action=createaccount&name=testuser&password=test123',
297 'api.php?action=createaccount&name=testmailuser&mailpassword=true&reason=MyReason',
301 public function getHelpUrls() {
302 return 'https://www.mediawiki.org/wiki/API:Account_creation';