Aashish's fix for bug33997 (SpecialPasswordReset does not always has the correct...
[lhc/web/wiklou.git] / includes / specials / SpecialUserlogin.php
1 <?php
2 /**
3 * Implements Special:UserLogin
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup SpecialPage
22 */
23
24 /**
25 * Implements Special:UserLogin
26 *
27 * @ingroup SpecialPage
28 */
29 class LoginForm extends SpecialPage {
30
31 const SUCCESS = 0;
32 const NO_NAME = 1;
33 const ILLEGAL = 2;
34 const WRONG_PLUGIN_PASS = 3;
35 const NOT_EXISTS = 4;
36 const WRONG_PASS = 5;
37 const EMPTY_PASS = 6;
38 const RESET_PASS = 7;
39 const ABORTED = 8;
40 const CREATE_BLOCKED = 9;
41 const THROTTLED = 10;
42 const USER_BLOCKED = 11;
43 const NEED_TOKEN = 12;
44 const WRONG_TOKEN = 13;
45
46 var $mUsername, $mPassword, $mRetype, $mReturnTo, $mCookieCheck, $mPosted;
47 var $mAction, $mCreateaccount, $mCreateaccountMail;
48 var $mLoginattempt, $mRemember, $mEmail, $mDomain, $mLanguage;
49 var $mSkipCookieCheck, $mReturnToQuery, $mToken, $mStickHTTPS;
50 var $mType, $mReason, $mRealName;
51 var $mAbortLoginErrorMsg = 'login-abort-generic';
52 private $mLoaded = false;
53
54 /**
55 * @var ExternalUser
56 */
57 private $mExtUser = null;
58
59 /**
60 * @ var WebRequest
61 */
62 private $mOverrideRequest = null;
63
64 /**
65 * @param WebRequest $request
66 */
67 public function __construct( $request = null ) {
68 parent::__construct( 'Userlogin' );
69
70 $this->mOverrideRequest = $request;
71 }
72
73 /**
74 * Loader
75 */
76 function load() {
77 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail, $wgRedirectOnLogin;
78
79 if ( $this->mLoaded ) {
80 return;
81 }
82 $this->mLoaded = true;
83
84 if ( $this->mOverrideRequest === null ) {
85 $request = $this->getRequest();
86 } else {
87 $request = $this->mOverrideRequest;
88 }
89
90 $this->mType = $request->getText( 'type' );
91 $this->mUsername = $request->getText( 'wpName' );
92 $this->mPassword = $request->getText( 'wpPassword' );
93 $this->mRetype = $request->getText( 'wpRetype' );
94 $this->mDomain = $request->getText( 'wpDomain' );
95 $this->mReason = $request->getText( 'wpReason' );
96 $this->mReturnTo = $request->getVal( 'returnto' );
97 $this->mReturnToQuery = $request->getVal( 'returntoquery' );
98 $this->mCookieCheck = $request->getVal( 'wpCookieCheck' );
99 $this->mPosted = $request->wasPosted();
100 $this->mCreateaccount = $request->getCheck( 'wpCreateaccount' );
101 $this->mCreateaccountMail = $request->getCheck( 'wpCreateaccountMail' )
102 && $wgEnableEmail;
103 $this->mLoginattempt = $request->getCheck( 'wpLoginattempt' );
104 $this->mAction = $request->getVal( 'action' );
105 $this->mRemember = $request->getCheck( 'wpRemember' );
106 $this->mStickHTTPS = $request->getCheck( 'wpStickHTTPS' );
107 $this->mLanguage = $request->getText( 'uselang' );
108 $this->mSkipCookieCheck = $request->getCheck( 'wpSkipCookieCheck' );
109 $this->mToken = ( $this->mType == 'signup' ) ? $request->getVal( 'wpCreateaccountToken' ) : $request->getVal( 'wpLoginToken' );
110
111 if ( $wgRedirectOnLogin ) {
112 $this->mReturnTo = $wgRedirectOnLogin;
113 $this->mReturnToQuery = '';
114 }
115
116 if( $wgEnableEmail ) {
117 $this->mEmail = $request->getText( 'wpEmail' );
118 } else {
119 $this->mEmail = '';
120 }
121 if( !in_array( 'realname', $wgHiddenPrefs ) ) {
122 $this->mRealName = $request->getText( 'wpRealName' );
123 } else {
124 $this->mRealName = '';
125 }
126
127 if( !$wgAuth->validDomain( $this->mDomain ) ) {
128 if ( isset( $_SESSION['wsDomain'] ) ) {
129 $this->mDomain = $_SESSION['wsDomain'];
130 } else {
131 $this->mDomain = 'invaliddomain';
132 }
133 }
134 $wgAuth->setDomain( $this->mDomain );
135
136 # 1. When switching accounts, it sucks to get automatically logged out
137 # 2. Do not return to PasswordReset after a successful password change
138 # but goto Wiki start page (Main_Page) instead ( bug 33997 )
139 $returnToTitle = Title::newFromText( $this->mReturnTo );
140 if( is_object( $returnToTitle ) && (
141 $returnToTitle->isSpecial( 'Userlogout' )
142 || $returnToTitle->isSpecial( 'PasswordReset' ) ) ) {
143 $this->mReturnTo = '';
144 $this->mReturnToQuery = '';
145 }
146 }
147
148 function getDescription() {
149 return $this->msg( $this->getUser()->isAllowed( 'createaccount' ) ?
150 'userlogin' : 'userloginnocreate' )->text();
151 }
152
153 public function execute( $par ) {
154 if ( session_id() == '' ) {
155 wfSetupSession();
156 }
157
158 $this->load();
159 $this->setHeaders();
160
161 if ( $par == 'signup' ) { # Check for [[Special:Userlogin/signup]]
162 $this->mType = 'signup';
163 }
164
165 if ( !is_null( $this->mCookieCheck ) ) {
166 $this->onCookieRedirectCheck( $this->mCookieCheck );
167 return;
168 } elseif( $this->mPosted ) {
169 if( $this->mCreateaccount ) {
170 return $this->addNewAccount();
171 } elseif ( $this->mCreateaccountMail ) {
172 return $this->addNewAccountMailPassword();
173 } elseif ( ( 'submitlogin' == $this->mAction ) || $this->mLoginattempt ) {
174 return $this->processLogin();
175 }
176 }
177 $this->mainLoginForm( '' );
178 }
179
180 /**
181 * @private
182 */
183 function addNewAccountMailPassword() {
184 if ( $this->mEmail == '' ) {
185 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
186 return;
187 }
188
189 $u = $this->addNewaccountInternal();
190
191 if ( $u == null ) {
192 return;
193 }
194
195 // Wipe the initial password and mail a temporary one
196 $u->setPassword( null );
197 $u->saveSettings();
198 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
199
200 wfRunHooks( 'AddNewAccount', array( $u, true ) );
201 $u->addNewUserLogEntry( true, $this->mReason );
202
203 $out = $this->getOutput();
204 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
205
206 if( !$result->isGood() ) {
207 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
208 } else {
209 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
210 $out->returnToMain( false );
211 }
212 }
213
214 /**
215 * @private
216 * @return bool|void
217 */
218 function addNewAccount() {
219 global $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
220
221 # Create the account and abort if there's a problem doing so
222 $u = $this->addNewAccountInternal();
223 if( $u == null ) {
224 return;
225 }
226
227 # If we showed up language selection links, and one was in use, be
228 # smart (and sensible) and save that language as the user's preference
229 if( $wgLoginLanguageSelector && $this->mLanguage ) {
230 $u->setOption( 'language', $this->mLanguage );
231 }
232
233 $out = $this->getOutput();
234
235 # Send out an email authentication message if needed
236 if( $wgEmailAuthentication && Sanitizer::validateEmail( $u->getEmail() ) ) {
237 $status = $u->sendConfirmationMail();
238 if( $status->isGood() ) {
239 $out->addWikiMsg( 'confirmemail_oncreate' );
240 } else {
241 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
242 }
243 }
244
245 # Save settings (including confirmation token)
246 $u->saveSettings();
247
248 # If not logged in, assume the new account as the current one and set
249 # session cookies then show a "welcome" message or a "need cookies"
250 # message as needed
251 if( $this->getUser()->isAnon() ) {
252 $u->setCookies();
253 $wgUser = $u;
254 // This should set it for OutputPage and the Skin
255 // which is needed or the personal links will be
256 // wrong.
257 $this->getContext()->setUser( $u );
258 wfRunHooks( 'AddNewAccount', array( $u, false ) );
259 $u->addNewUserLogEntry();
260 if( $this->hasSessionCookie() ) {
261 return $this->successfulCreation();
262 } else {
263 return $this->cookieRedirectCheck( 'new' );
264 }
265 } else {
266 # Confirm that the account was created
267 $out->setPageTitle( $this->msg( 'accountcreated' ) );
268 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
269 $out->returnToMain( false, $this->getTitle() );
270 wfRunHooks( 'AddNewAccount', array( $u, false ) );
271 $u->addNewUserLogEntry( false, $this->mReason );
272 return true;
273 }
274 }
275
276 /**
277 * @private
278 * @return bool|\User
279 */
280 function addNewAccountInternal() {
281 global $wgAuth, $wgMemc, $wgAccountCreationThrottle,
282 $wgMinimalPasswordLength, $wgEmailConfirmToEdit;
283
284 // If the user passes an invalid domain, something is fishy
285 if( !$wgAuth->validDomain( $this->mDomain ) ) {
286 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
287 return false;
288 }
289
290 // If we are not allowing users to login locally, we should be checking
291 // to see if the user is actually able to authenticate to the authenti-
292 // cation server before they create an account (otherwise, they can
293 // create a local account and login as any domain user). We only need
294 // to check this for domains that aren't local.
295 if( 'local' != $this->mDomain && $this->mDomain != '' ) {
296 if( !$wgAuth->canCreateAccounts() && ( !$wgAuth->userExists( $this->mUsername )
297 || !$wgAuth->authenticate( $this->mUsername, $this->mPassword ) ) ) {
298 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
299 return false;
300 }
301 }
302
303 if ( wfReadOnly() ) {
304 throw new ReadOnlyError;
305 }
306
307 # Request forgery checks.
308 if ( !self::getCreateaccountToken() ) {
309 self::setCreateaccountToken();
310 $this->mainLoginForm( $this->msg( 'nocookiesfornew' )->parse() );
311 return false;
312 }
313
314 # The user didn't pass a createaccount token
315 if ( !$this->mToken ) {
316 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
317 return false;
318 }
319
320 # Validate the createaccount token
321 if ( $this->mToken !== self::getCreateaccountToken() ) {
322 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
323 return false;
324 }
325
326 # Check permissions
327 $currentUser = $this->getUser();
328 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
329 throw new PermissionsError( 'createaccount' );
330 } elseif ( $currentUser->isBlockedFromCreateAccount() ) {
331 $this->userBlockedMessage( $currentUser->isBlockedFromCreateAccount() );
332 return false;
333 }
334
335 $ip = $this->getRequest()->getIP();
336 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
337 $this->mainLoginForm( $this->msg( 'sorbs_create_account_reason' )->text() . ' (' . htmlspecialchars( $ip ) . ')' );
338 return false;
339 }
340
341 # Now create a dummy user ($u) and check if it is valid
342 $name = trim( $this->mUsername );
343 $u = User::newFromName( $name, 'creatable' );
344 if ( !is_object( $u ) ) {
345 $this->mainLoginForm( $this->msg( 'noname' )->text() );
346 return false;
347 }
348
349 if ( 0 != $u->idForName() ) {
350 $this->mainLoginForm( $this->msg( 'userexists' )->text() );
351 return false;
352 }
353
354 if ( 0 != strcmp( $this->mPassword, $this->mRetype ) ) {
355 $this->mainLoginForm( $this->msg( 'badretype' )->text() );
356 return false;
357 }
358
359 # check for minimal password length
360 $valid = $u->getPasswordValidity( $this->mPassword );
361 if ( $valid !== true ) {
362 if ( !$this->mCreateaccountMail ) {
363 if ( is_array( $valid ) ) {
364 $message = array_shift( $valid );
365 $params = $valid;
366 } else {
367 $message = $valid;
368 $params = array( $wgMinimalPasswordLength );
369 }
370 $this->mainLoginForm( $this->msg( $message, $params )->text() );
371 return false;
372 } else {
373 # do not force a password for account creation by email
374 # set invalid password, it will be replaced later by a random generated password
375 $this->mPassword = null;
376 }
377 }
378
379 # if you need a confirmed email address to edit, then obviously you
380 # need an email address.
381 if ( $wgEmailConfirmToEdit && empty( $this->mEmail ) ) {
382 $this->mainLoginForm( $this->msg( 'noemailtitle' )->text() );
383 return false;
384 }
385
386 if( !empty( $this->mEmail ) && !Sanitizer::validateEmail( $this->mEmail ) ) {
387 $this->mainLoginForm( $this->msg( 'invalidemailaddress' )->text() );
388 return false;
389 }
390
391 # Set some additional data so the AbortNewAccount hook can be used for
392 # more than just username validation
393 $u->setEmail( $this->mEmail );
394 $u->setRealName( $this->mRealName );
395
396 $abortError = '';
397 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
398 // Hook point to add extra creation throttles and blocks
399 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
400 $this->mainLoginForm( $abortError );
401 return false;
402 }
403
404 // Hook point to check for exempt from account creation throttle
405 if ( !wfRunHooks( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
406 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook allowed account creation w/o throttle\n" );
407 } else {
408 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
409 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
410 $value = $wgMemc->get( $key );
411 if ( !$value ) {
412 $wgMemc->set( $key, 0, 86400 );
413 }
414 if ( $value >= $wgAccountCreationThrottle ) {
415 $this->throttleHit( $wgAccountCreationThrottle );
416 return false;
417 }
418 $wgMemc->incr( $key );
419 }
420 }
421
422 if( !$wgAuth->addUser( $u, $this->mPassword, $this->mEmail, $this->mRealName ) ) {
423 $this->mainLoginForm( $this->msg( 'externaldberror' )->text() );
424 return false;
425 }
426
427 self::clearCreateaccountToken();
428 return $this->initUser( $u, false );
429 }
430
431 /**
432 * Actually add a user to the database.
433 * Give it a User object that has been initialised with a name.
434 *
435 * @param $u User object.
436 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
437 * @return User object.
438 * @private
439 */
440 function initUser( $u, $autocreate ) {
441 global $wgAuth;
442
443 $u->addToDatabase();
444
445 if ( $wgAuth->allowPasswordChange() ) {
446 $u->setPassword( $this->mPassword );
447 }
448
449 $u->setEmail( $this->mEmail );
450 $u->setRealName( $this->mRealName );
451 $u->setToken();
452
453 $wgAuth->initUser( $u, $autocreate );
454
455 if ( $this->mExtUser ) {
456 $this->mExtUser->linkToLocal( $u->getId() );
457 $email = $this->mExtUser->getPref( 'emailaddress' );
458 if ( $email && !$this->mEmail ) {
459 $u->setEmail( $email );
460 }
461 }
462
463 $u->setOption( 'rememberpassword', $this->mRemember ? 1 : 0 );
464 $u->saveSettings();
465
466 # Update user count
467 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
468 $ssUpdate->doUpdate();
469
470 return $u;
471 }
472
473 /**
474 * Internally authenticate the login request.
475 *
476 * This may create a local account as a side effect if the
477 * authentication plugin allows transparent local account
478 * creation.
479 * @return int
480 */
481 public function authenticateUserData() {
482 global $wgUser, $wgAuth;
483
484 $this->load();
485
486 if ( $this->mUsername == '' ) {
487 return self::NO_NAME;
488 }
489
490 // We require a login token to prevent login CSRF
491 // Handle part of this before incrementing the throttle so
492 // token-less login attempts don't count towards the throttle
493 // but wrong-token attempts do.
494
495 // If the user doesn't have a login token yet, set one.
496 if ( !self::getLoginToken() ) {
497 self::setLoginToken();
498 return self::NEED_TOKEN;
499 }
500 // If the user didn't pass a login token, tell them we need one
501 if ( !$this->mToken ) {
502 return self::NEED_TOKEN;
503 }
504
505 $throttleCount = self::incLoginThrottle( $this->mUsername );
506 if ( $throttleCount === true ) {
507 return self::THROTTLED;
508 }
509
510 // Validate the login token
511 if ( $this->mToken !== self::getLoginToken() ) {
512 return self::WRONG_TOKEN;
513 }
514
515 // Load the current user now, and check to see if we're logging in as
516 // the same name. This is necessary because loading the current user
517 // (say by calling getName()) calls the UserLoadFromSession hook, which
518 // potentially creates the user in the database. Until we load $wgUser,
519 // checking for user existence using User::newFromName($name)->getId() below
520 // will effectively be using stale data.
521 if ( $this->getUser()->getName() === $this->mUsername ) {
522 wfDebug( __METHOD__ . ": already logged in as {$this->mUsername}\n" );
523 return self::SUCCESS;
524 }
525
526 $this->mExtUser = ExternalUser::newFromName( $this->mUsername );
527
528 # TODO: Allow some magic here for invalid external names, e.g., let the
529 # user choose a different wiki name.
530 $u = User::newFromName( $this->mUsername );
531 if( !( $u instanceof User ) || !User::isUsableName( $u->getName() ) ) {
532 return self::ILLEGAL;
533 }
534
535 $isAutoCreated = false;
536 if ( 0 == $u->getID() ) {
537 $status = $this->attemptAutoCreate( $u );
538 if ( $status !== self::SUCCESS ) {
539 return $status;
540 } else {
541 $isAutoCreated = true;
542 }
543 } else {
544 global $wgExternalAuthType, $wgAutocreatePolicy;
545 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
546 && is_object( $this->mExtUser )
547 && $this->mExtUser->authenticate( $this->mPassword ) ) {
548 # The external user and local user have the same name and
549 # password, so we assume they're the same.
550 $this->mExtUser->linkToLocal( $u->getID() );
551 }
552
553 $u->load();
554 }
555
556 // Give general extensions, such as a captcha, a chance to abort logins
557 $abort = self::ABORTED;
558 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword, &$abort, &$this->mAbortLoginErrorMsg ) ) ) {
559 return $abort;
560 }
561
562 global $wgBlockDisablesLogin;
563 if ( !$u->checkPassword( $this->mPassword ) ) {
564 if( $u->checkTemporaryPassword( $this->mPassword ) ) {
565 // The e-mailed temporary password should not be used for actu-
566 // al logins; that's a very sloppy habit, and insecure if an
567 // attacker has a few seconds to click "search" on someone's o-
568 // pen mail reader.
569 //
570 // Allow it to be used only to reset the password a single time
571 // to a new value, which won't be in the user's e-mail ar-
572 // chives.
573 //
574 // For backwards compatibility, we'll still recognize it at the
575 // login form to minimize surprises for people who have been
576 // logging in with a temporary password for some time.
577 //
578 // As a side-effect, we can authenticate the user's e-mail ad-
579 // dress if it's not already done, since the temporary password
580 // was sent via e-mail.
581 if( !$u->isEmailConfirmed() ) {
582 $u->confirmEmail();
583 $u->saveSettings();
584 }
585
586 // At this point we just return an appropriate code/ indicating
587 // that the UI should show a password reset form; bot inter-
588 // faces etc will probably just fail cleanly here.
589 $retval = self::RESET_PASS;
590 } else {
591 $retval = ( $this->mPassword == '' ) ? self::EMPTY_PASS : self::WRONG_PASS;
592 }
593 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
594 // If we've enabled it, make it so that a blocked user cannot login
595 $retval = self::USER_BLOCKED;
596 } else {
597 $wgAuth->updateUser( $u );
598 $wgUser = $u;
599 // This should set it for OutputPage and the Skin
600 // which is needed or the personal links will be
601 // wrong.
602 $this->getContext()->setUser( $u );
603
604 // Please reset throttle for successful logins, thanks!
605 if ( $throttleCount ) {
606 self::clearLoginThrottle( $this->mUsername );
607 }
608
609 if ( $isAutoCreated ) {
610 // Must be run after $wgUser is set, for correct new user log
611 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
612 }
613
614 $retval = self::SUCCESS;
615 }
616 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword, $retval ) );
617 return $retval;
618 }
619
620 /**
621 * Increment the login attempt throttle hit count for the (username,current IP)
622 * tuple unless the throttle was already reached.
623 * @param $username string The user name
624 * @return Bool|Integer The integer hit count or True if it is already at the limit
625 */
626 public static function incLoginThrottle( $username ) {
627 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
628 $username = trim( $username ); // sanity
629
630 $throttleCount = 0;
631 if ( is_array( $wgPasswordAttemptThrottle ) ) {
632 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
633 $count = $wgPasswordAttemptThrottle['count'];
634 $period = $wgPasswordAttemptThrottle['seconds'];
635
636 $throttleCount = $wgMemc->get( $throttleKey );
637 if ( !$throttleCount ) {
638 $wgMemc->add( $throttleKey, 1, $period ); // start counter
639 } elseif ( $throttleCount < $count ) {
640 $wgMemc->incr( $throttleKey );
641 } elseif ( $throttleCount >= $count ) {
642 return true;
643 }
644 }
645
646 return $throttleCount;
647 }
648
649 /**
650 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
651 * @param $username string The user name
652 * @return void
653 */
654 public static function clearLoginThrottle( $username ) {
655 global $wgMemc, $wgRequest;
656 $username = trim( $username ); // sanity
657
658 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
659 $wgMemc->delete( $throttleKey );
660 }
661
662 /**
663 * Attempt to automatically create a user on login. Only succeeds if there
664 * is an external authentication method which allows it.
665 *
666 * @param $user User
667 *
668 * @return integer Status code
669 */
670 function attemptAutoCreate( $user ) {
671 global $wgAuth, $wgAutocreatePolicy;
672
673 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
674 wfDebug( __METHOD__ . ": user is blocked from account creation\n" );
675 return self::CREATE_BLOCKED;
676 }
677
678 /**
679 * If the external authentication plugin allows it, automatically cre-
680 * ate a new account for users that are externally defined but have not
681 * yet logged in.
682 */
683 if ( $this->mExtUser ) {
684 # mExtUser is neither null nor false, so use the new ExternalAuth
685 # system.
686 if ( $wgAutocreatePolicy == 'never' ) {
687 return self::NOT_EXISTS;
688 }
689 if ( !$this->mExtUser->authenticate( $this->mPassword ) ) {
690 return self::WRONG_PLUGIN_PASS;
691 }
692 } else {
693 # Old AuthPlugin.
694 if ( !$wgAuth->autoCreate() ) {
695 return self::NOT_EXISTS;
696 }
697 if ( !$wgAuth->userExists( $user->getName() ) ) {
698 wfDebug( __METHOD__ . ": user does not exist\n" );
699 return self::NOT_EXISTS;
700 }
701 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword ) ) {
702 wfDebug( __METHOD__ . ": \$wgAuth->authenticate() returned false, aborting\n" );
703 return self::WRONG_PLUGIN_PASS;
704 }
705 }
706
707 $abortError = '';
708 if( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
709 // Hook point to add extra creation throttles and blocks
710 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
711 $this->mAbortLoginErrorMsg = $abortError;
712 return self::ABORTED;
713 }
714
715 wfDebug( __METHOD__ . ": creating account\n" );
716 $this->initUser( $user, true );
717 return self::SUCCESS;
718 }
719
720 function processLogin() {
721 global $wgMemc, $wgLang;
722
723 switch ( $this->authenticateUserData() ) {
724 case self::SUCCESS:
725 # We've verified now, update the real record
726 $user = $this->getUser();
727 if( (bool)$this->mRemember != (bool)$user->getOption( 'rememberpassword' ) ) {
728 $user->setOption( 'rememberpassword', $this->mRemember ? 1 : 0 );
729 $user->saveSettings();
730 } else {
731 $user->invalidateCache();
732 }
733 $user->setCookies();
734 self::clearLoginToken();
735
736 // Reset the throttle
737 $request = $this->getRequest();
738 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername ) );
739 $wgMemc->delete( $key );
740
741 if( $this->hasSessionCookie() || $this->mSkipCookieCheck ) {
742 /* Replace the language object to provide user interface in
743 * correct language immediately on this first page load.
744 */
745 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
746 $userLang = Language::factory( $code );
747 $wgLang = $userLang;
748 $this->getContext()->setLanguage( $userLang );
749 return $this->successfulLogin();
750 } else {
751 return $this->cookieRedirectCheck( 'login' );
752 }
753 break;
754
755 case self::NEED_TOKEN:
756 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
757 break;
758 case self::WRONG_TOKEN:
759 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
760 break;
761 case self::NO_NAME:
762 case self::ILLEGAL:
763 $this->mainLoginForm( $this->msg( 'noname' )->text() );
764 break;
765 case self::WRONG_PLUGIN_PASS:
766 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
767 break;
768 case self::NOT_EXISTS:
769 if( $this->getUser()->isAllowed( 'createaccount' ) ) {
770 $this->mainLoginForm( $this->msg( 'nosuchuser',
771 wfEscapeWikiText( $this->mUsername ) )->parse() );
772 } else {
773 $this->mainLoginForm( $this->msg( 'nosuchusershort',
774 wfEscapeWikiText( $this->mUsername ) )->text() );
775 }
776 break;
777 case self::WRONG_PASS:
778 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
779 break;
780 case self::EMPTY_PASS:
781 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
782 break;
783 case self::RESET_PASS:
784 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
785 break;
786 case self::CREATE_BLOCKED:
787 $this->userBlockedMessage( $this->getUser()->mBlock );
788 break;
789 case self::THROTTLED:
790 $this->mainLoginForm( $this->msg( 'login-throttled' )->text() );
791 break;
792 case self::USER_BLOCKED:
793 $this->mainLoginForm( $this->msg( 'login-userblocked',
794 $this->mUsername )->escaped() );
795 break;
796 case self::ABORTED:
797 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg )->text() );
798 break;
799 default:
800 throw new MWException( 'Unhandled case value' );
801 }
802 }
803
804 function resetLoginForm( $error ) {
805 $this->getOutput()->addHTML( Xml::element('p', array( 'class' => 'error' ), $error ) );
806 $reset = new SpecialChangePassword();
807 $reset->setContext( $this );
808 $reset->execute( null );
809 }
810
811 /**
812 * @param $u User object
813 * @param $throttle Boolean
814 * @param $emailTitle String: message name of email title
815 * @param $emailText String: message name of email text
816 * @return Status object
817 */
818 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
819 global $wgServer, $wgScript, $wgNewPasswordExpiry;
820
821 if ( $u->getEmail() == '' ) {
822 return Status::newFatal( 'noemail', $u->getName() );
823 }
824 $ip = $this->getRequest()->getIP();
825 if( !$ip ) {
826 return Status::newFatal( 'badipaddress' );
827 }
828
829 $currentUser = $this->getUser();
830 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
831
832 $np = $u->randomPassword();
833 $u->setNewpassword( $np, $throttle );
834 $u->saveSettings();
835 $userLanguage = $u->getOption( 'language' );
836 $m = $this->msg( $emailText, $ip, $u->getName(), $np, $wgServer . $wgScript,
837 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
838 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
839
840 return $result;
841 }
842
843
844 /**
845 * Run any hooks registered for logins, then HTTP redirect to
846 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
847 * nice message here, but that's really not as useful as just being sent to
848 * wherever you logged in from. It should be clear that the action was
849 * successful, given the lack of error messages plus the appearance of your
850 * name in the upper right.
851 *
852 * @private
853 */
854 function successfulLogin() {
855 # Run any hooks; display injected HTML if any, else redirect
856 $currentUser = $this->getUser();
857 $injected_html = '';
858 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
859
860 if( $injected_html !== '' ) {
861 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
862 } else {
863 $titleObj = Title::newFromText( $this->mReturnTo );
864 if ( !$titleObj instanceof Title ) {
865 $titleObj = Title::newMainPage();
866 }
867 $redirectUrl = $titleObj->getFullURL( $this->mReturnToQuery );
868 global $wgSecureLogin;
869 if( $wgSecureLogin && !$this->mStickHTTPS ) {
870 $redirectUrl = preg_replace( '/^https:/', 'http:', $redirectUrl );
871 }
872 $this->getOutput()->redirect( $redirectUrl );
873 }
874 }
875
876 /**
877 * Run any hooks registered for logins, then display a message welcoming
878 * the user.
879 *
880 * @private
881 */
882 function successfulCreation() {
883 # Run any hooks; display injected HTML
884 $currentUser = $this->getUser();
885 $injected_html = '';
886 $welcome_creation_msg = 'welcomecreation';
887
888 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
889
890 /**
891 * Let any extensions change what message is shown.
892 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
893 * @since 1.18
894 */
895 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
896
897 $this->displaySuccessfulLogin( $welcome_creation_msg, $injected_html );
898 }
899
900 /**
901 * Display a "login successful" page.
902 */
903 private function displaySuccessfulLogin( $msgname, $injected_html ) {
904 $out = $this->getOutput();
905 $out->setPageTitle( $this->msg( 'loginsuccesstitle' ) );
906 if( $msgname ){
907 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
908 }
909
910 $out->addHTML( $injected_html );
911
912 if ( !empty( $this->mReturnTo ) ) {
913 $out->returnToMain( null, $this->mReturnTo, $this->mReturnToQuery );
914 } else {
915 $out->returnToMain( null );
916 }
917 }
918
919 /**
920 * Output a message that informs the user that they cannot create an account because
921 * there is a block on them or their IP which prevents account creation. Note that
922 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
923 * setting on blocks (bug 13611).
924 * @param $block Block the block causing this error
925 */
926 function userBlockedMessage( Block $block ) {
927 # Let's be nice about this, it's likely that this feature will be used
928 # for blocking large numbers of innocent people, e.g. range blocks on
929 # schools. Don't blame it on the user. There's a small chance that it
930 # really is the user's fault, i.e. the username is blocked and they
931 # haven't bothered to log out before trying to create an account to
932 # evade it, but we'll leave that to their guilty conscience to figure
933 # out.
934
935 $out = $this->getOutput();
936 $out->setPageTitle( $this->msg( 'cantcreateaccounttitle' ) );
937
938 $block_reason = $block->mReason;
939 if ( strval( $block_reason ) === '' ) {
940 $block_reason = $this->msg( 'blockednoreason' )->text();
941 }
942
943 $out->addWikiMsg(
944 'cantcreateaccount-text',
945 $block->getTarget(),
946 $block_reason,
947 $block->getByName()
948 );
949
950 $out->returnToMain( false );
951 }
952
953 /**
954 * @private
955 */
956 function mainLoginForm( $msg, $msgtype = 'error' ) {
957 global $wgEnableEmail, $wgEnableUserEmail;
958 global $wgHiddenPrefs, $wgLoginLanguageSelector;
959 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
960 global $wgSecureLogin, $wgPasswordResetRoutes;
961
962 $titleObj = $this->getTitle();
963 $user = $this->getUser();
964
965 if ( $this->mType == 'signup' ) {
966 // Block signup here if in readonly. Keeps user from
967 // going through the process (filling out data, etc)
968 // and being informed later.
969 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
970 if ( count( $permErrors ) ) {
971 throw new PermissionsError( 'createaccount', $permErrors );
972 } elseif ( $user->isBlockedFromCreateAccount() ) {
973 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
974 return;
975 } elseif ( wfReadOnly() ) {
976 throw new ReadOnlyError;
977 }
978 }
979
980 if ( $this->mUsername == '' ) {
981 if ( $user->isLoggedIn() ) {
982 $this->mUsername = $user->getName();
983 } else {
984 $this->mUsername = $this->getRequest()->getCookie( 'UserName' );
985 }
986 }
987
988 if ( $this->mType == 'signup' ) {
989 $template = new UsercreateTemplate();
990 $q = 'action=submitlogin&type=signup';
991 $linkq = 'type=login';
992 $linkmsg = 'gotaccount';
993 } else {
994 $template = new UserloginTemplate();
995 $q = 'action=submitlogin&type=login';
996 $linkq = 'type=signup';
997 $linkmsg = 'nologin';
998 }
999
1000 if ( !empty( $this->mReturnTo ) ) {
1001 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
1002 if ( !empty( $this->mReturnToQuery ) ) {
1003 $returnto .= '&returntoquery=' .
1004 wfUrlencode( $this->mReturnToQuery );
1005 }
1006 $q .= $returnto;
1007 $linkq .= $returnto;
1008 }
1009
1010 # Don't show a "create account" link if the user can't
1011 if( $this->showCreateOrLoginLink( $user ) ) {
1012 # Pass any language selection on to the mode switch link
1013 if( $wgLoginLanguageSelector && $this->mLanguage ) {
1014 $linkq .= '&uselang=' . $this->mLanguage;
1015 }
1016 $link = Html::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
1017 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1018
1019 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1020 } else {
1021 $template->set( 'link', '' );
1022 }
1023
1024 $resetLink = $this->mType == 'signup'
1025 ? null
1026 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1027
1028 $template->set( 'header', '' );
1029 $template->set( 'name', $this->mUsername );
1030 $template->set( 'password', $this->mPassword );
1031 $template->set( 'retype', $this->mRetype );
1032 $template->set( 'email', $this->mEmail );
1033 $template->set( 'realname', $this->mRealName );
1034 $template->set( 'domain', $this->mDomain );
1035 $template->set( 'reason', $this->mReason );
1036
1037 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1038 $template->set( 'message', $msg );
1039 $template->set( 'messagetype', $msgtype );
1040 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1041 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1042 $template->set( 'useemail', $wgEnableEmail );
1043 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1044 $template->set( 'emailothers', $wgEnableUserEmail );
1045 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1046 $template->set( 'resetlink', $resetLink );
1047 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1048 $template->set( 'usereason', $user->isLoggedIn() );
1049 $template->set( 'remember', $user->getOption( 'rememberpassword' ) || $this->mRemember );
1050 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1051 $template->set( 'stickHTTPS', $this->mStickHTTPS );
1052
1053 if ( $this->mType == 'signup' ) {
1054 if ( !self::getCreateaccountToken() ) {
1055 self::setCreateaccountToken();
1056 }
1057 $template->set( 'token', self::getCreateaccountToken() );
1058 } else {
1059 if ( !self::getLoginToken() ) {
1060 self::setLoginToken();
1061 }
1062 $template->set( 'token', self::getLoginToken() );
1063 }
1064
1065 # Prepare language selection links as needed
1066 if( $wgLoginLanguageSelector ) {
1067 $template->set( 'languages', $this->makeLanguageSelector() );
1068 if( $this->mLanguage ) {
1069 $template->set( 'uselang', $this->mLanguage );
1070 }
1071 }
1072
1073 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1074 // Ditto for signupend
1075 $usingHTTPS = WebRequest::detectProtocol() == 'https';
1076 $loginendHTTPS = $this->msg( 'loginend-https' );
1077 $signupendHTTPS = $this->msg( 'signupend-https' );
1078 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1079 $template->set( 'loginend', $loginendHTTPS->parse() );
1080 } else {
1081 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1082 }
1083 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1084 $template->set( 'signupend', $signupendHTTPS->parse() );
1085 } else {
1086 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1087 }
1088
1089 // Give authentication and captcha plugins a chance to modify the form
1090 $wgAuth->modifyUITemplate( $template, $this->mType );
1091 if ( $this->mType == 'signup' ) {
1092 wfRunHooks( 'UserCreateForm', array( &$template ) );
1093 } else {
1094 wfRunHooks( 'UserLoginForm', array( &$template ) );
1095 }
1096
1097 $out = $this->getOutput();
1098 $out->disallowUserJs(); // just in case...
1099 $out->addTemplate( $template );
1100 }
1101
1102 /**
1103 * @private
1104 *
1105 * @param $user User
1106 *
1107 * @return Boolean
1108 */
1109 function showCreateOrLoginLink( &$user ) {
1110 if( $this->mType == 'signup' ) {
1111 return true;
1112 } elseif( $user->isAllowed( 'createaccount' ) ) {
1113 return true;
1114 } else {
1115 return false;
1116 }
1117 }
1118
1119 /**
1120 * Check if a session cookie is present.
1121 *
1122 * This will not pick up a cookie set during _this_ request, but is meant
1123 * to ensure that the client is returning the cookie which was set on a
1124 * previous pass through the system.
1125 *
1126 * @private
1127 * @return bool
1128 */
1129 function hasSessionCookie() {
1130 global $wgDisableCookieCheck;
1131 return $wgDisableCookieCheck ? true : $this->getRequest()->checkSessionCookie();
1132 }
1133
1134 /**
1135 * Get the login token from the current session
1136 * @return Mixed
1137 */
1138 public static function getLoginToken() {
1139 global $wgRequest;
1140 return $wgRequest->getSessionData( 'wsLoginToken' );
1141 }
1142
1143 /**
1144 * Randomly generate a new login token and attach it to the current session
1145 */
1146 public static function setLoginToken() {
1147 global $wgRequest;
1148 // Use User::generateToken() instead of $user->editToken()
1149 // because the latter reuses $_SESSION['wsEditToken']
1150 $wgRequest->setSessionData( 'wsLoginToken', User::generateToken() );
1151 }
1152
1153 /**
1154 * Remove any login token attached to the current session
1155 */
1156 public static function clearLoginToken() {
1157 global $wgRequest;
1158 $wgRequest->setSessionData( 'wsLoginToken', null );
1159 }
1160
1161 /**
1162 * Get the createaccount token from the current session
1163 * @return Mixed
1164 */
1165 public static function getCreateaccountToken() {
1166 global $wgRequest;
1167 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1168 }
1169
1170 /**
1171 * Randomly generate a new createaccount token and attach it to the current session
1172 */
1173 public static function setCreateaccountToken() {
1174 global $wgRequest;
1175 $wgRequest->setSessionData( 'wsCreateaccountToken', User::generateToken() );
1176 }
1177
1178 /**
1179 * Remove any createaccount token attached to the current session
1180 */
1181 public static function clearCreateaccountToken() {
1182 global $wgRequest;
1183 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1184 }
1185
1186 /**
1187 * @private
1188 * @return void
1189 */
1190 function cookieRedirectCheck( $type ) {
1191 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
1192 $query = array( 'wpCookieCheck' => $type );
1193 if ( $this->mReturnTo ) {
1194 $query['returnto'] = $this->mReturnTo;
1195 }
1196 $check = $titleObj->getFullURL( $query );
1197
1198 return $this->getOutput()->redirect( $check );
1199 }
1200
1201 /**
1202 * @private
1203 */
1204 function onCookieRedirectCheck( $type ) {
1205 if ( !$this->hasSessionCookie() ) {
1206 if ( $type == 'new' ) {
1207 return $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1208 } elseif ( $type == 'login' ) {
1209 return $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1210 } else {
1211 # shouldn't happen
1212 return $this->mainLoginForm( $this->msg( 'error' )->text() );
1213 }
1214 } else {
1215 return $this->successfulLogin();
1216 }
1217 }
1218
1219 /**
1220 * @private
1221 */
1222 function throttleHit( $limit ) {
1223 $this->mainLoginForm( $this->msg( 'acct_creation_throttle_hit' )->numParams( $limit )->parse() );
1224 }
1225
1226 /**
1227 * Produce a bar of links which allow the user to select another language
1228 * during login/registration but retain "returnto"
1229 *
1230 * @return string
1231 */
1232 function makeLanguageSelector() {
1233 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1234 if( !$msg->isBlank() ) {
1235 $langs = explode( "\n", $msg->text() );
1236 $links = array();
1237 foreach( $langs as $lang ) {
1238 $lang = trim( $lang, '* ' );
1239 $parts = explode( '|', $lang );
1240 if ( count( $parts ) >= 2 ) {
1241 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1242 }
1243 }
1244 return count( $links ) > 0 ? $this->msg( 'loginlanguagelabel' )->rawParams(
1245 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1246 } else {
1247 return '';
1248 }
1249 }
1250
1251 /**
1252 * Create a language selector link for a particular language
1253 * Links back to this page preserving type and returnto
1254 *
1255 * @param $text Link text
1256 * @param $lang Language code
1257 * @return string
1258 */
1259 function makeLanguageSelectorLink( $text, $lang ) {
1260 $attr = array( 'uselang' => $lang );
1261 if( $this->mType == 'signup' ) {
1262 $attr['type'] = 'signup';
1263 }
1264 if( $this->mReturnTo ) {
1265 $attr['returnto'] = $this->mReturnTo;
1266 }
1267 return Linker::linkKnown(
1268 $this->getTitle(),
1269 htmlspecialchars( $text ),
1270 array(),
1271 $attr
1272 );
1273 }
1274 }