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