Merge "Fix positioning of jQuery.tipsy tooltip arrows"
[mediawiki.git] / includes / specials / SpecialUserlogin.php
blobfec1e3a5db736c81f60e39f818d62135f6f1eb38
1 <?php
2 /**
3 * Implements Special:UserLogin
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.
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.
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
20 * @file
21 * @ingroup SpecialPage
23 use MediaWiki\Logger\LoggerFactory;
25 /**
26 * Implements Special:UserLogin
28 * @ingroup SpecialPage
30 class LoginForm extends SpecialPage {
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 const USER_MIGRATED = 14;
47 public static $statusCodes = array(
48 self::SUCCESS => 'success',
49 self::NO_NAME => 'no_name',
50 self::ILLEGAL => 'illegal',
51 self::WRONG_PLUGIN_PASS => 'wrong_plugin_pass',
52 self::NOT_EXISTS => 'not_exists',
53 self::WRONG_PASS => 'wrong_pass',
54 self::EMPTY_PASS => 'empty_pass',
55 self::RESET_PASS => 'reset_pass',
56 self::ABORTED => 'aborted',
57 self::CREATE_BLOCKED => 'create_blocked',
58 self::THROTTLED => 'throttled',
59 self::USER_BLOCKED => 'user_blocked',
60 self::NEED_TOKEN => 'need_token',
61 self::WRONG_TOKEN => 'wrong_token',
62 self::USER_MIGRATED => 'user_migrated',
65 /**
66 * Valid error and warning messages
68 * Special:Userlogin can show an error or warning message on the form when
69 * coming from another page. This is done via the ?error= or ?warning= GET
70 * parameters.
72 * This array is the list of valid message keys. All other values will be
73 * ignored.
75 * @since 1.24
76 * @var string[]
78 public static $validErrorMessages = array(
79 'exception-nologin-text',
80 'watchlistanontext',
81 'changeemail-no-info',
82 'resetpass-no-info',
83 'confirmemail_needlogin',
84 'prefsnologintext2',
87 public $mAbortLoginErrorMsg = null;
89 protected $mUsername;
90 protected $mPassword;
91 protected $mRetype;
92 protected $mReturnTo;
93 protected $mCookieCheck;
94 protected $mPosted;
95 protected $mAction;
96 protected $mCreateaccount;
97 protected $mCreateaccountMail;
98 protected $mLoginattempt;
99 protected $mRemember;
100 protected $mEmail;
101 protected $mDomain;
102 protected $mLanguage;
103 protected $mSkipCookieCheck;
104 protected $mReturnToQuery;
105 protected $mToken;
106 protected $mStickHTTPS;
107 protected $mType;
108 protected $mReason;
109 protected $mRealName;
110 protected $mEntryError = '';
111 protected $mEntryErrorType = 'error';
113 private $mTempPasswordUsed;
114 private $mLoaded = false;
115 private $mSecureLoginUrl;
117 /** @var WebRequest */
118 private $mOverrideRequest = null;
120 /** @var WebRequest Effective request; set at the beginning of load */
121 private $mRequest = null;
124 * @param WebRequest $request
126 public function __construct( $request = null ) {
127 global $wgUseMediaWikiUIEverywhere;
128 parent::__construct( 'Userlogin' );
130 $this->mOverrideRequest = $request;
131 // Override UseMediaWikiEverywhere to true, to force login and create form to use mw ui
132 $wgUseMediaWikiUIEverywhere = true;
136 * Returns an array of all valid error messages.
138 * @return array
140 public static function getValidErrorMessages() {
141 static $messages = null;
142 if ( !$messages ) {
143 $messages = self::$validErrorMessages;
144 Hooks::run( 'LoginFormValidErrorMessages', array( &$messages ) );
147 return $messages;
151 * Loader
153 function load() {
154 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail;
156 if ( $this->mLoaded ) {
157 return;
159 $this->mLoaded = true;
161 if ( $this->mOverrideRequest === null ) {
162 $request = $this->getRequest();
163 } else {
164 $request = $this->mOverrideRequest;
166 $this->mRequest = $request;
168 $this->mType = $request->getText( 'type' );
169 $this->mUsername = $request->getText( 'wpName' );
170 $this->mPassword = $request->getText( 'wpPassword' );
171 $this->mRetype = $request->getText( 'wpRetype' );
172 $this->mDomain = $request->getText( 'wpDomain' );
173 $this->mReason = $request->getText( 'wpReason' );
174 $this->mCookieCheck = $request->getVal( 'wpCookieCheck' );
175 $this->mPosted = $request->wasPosted();
176 $this->mCreateaccountMail = $request->getCheck( 'wpCreateaccountMail' )
177 && $wgEnableEmail;
178 $this->mCreateaccount = $request->getCheck( 'wpCreateaccount' ) && !$this->mCreateaccountMail;
179 $this->mLoginattempt = $request->getCheck( 'wpLoginattempt' );
180 $this->mAction = $request->getVal( 'action' );
181 $this->mRemember = $request->getCheck( 'wpRemember' );
182 $this->mFromHTTP = $request->getBool( 'fromhttp', false )
183 || $request->getBool( 'wpFromhttp', false );
184 $this->mStickHTTPS = ( !$this->mFromHTTP && $request->getProtocol() === 'https' )
185 || $request->getBool( 'wpForceHttps', false );
186 $this->mLanguage = $request->getText( 'uselang' );
187 $this->mSkipCookieCheck = $request->getCheck( 'wpSkipCookieCheck' );
188 $this->mToken = $this->mType == 'signup'
189 ? $request->getVal( 'wpCreateaccountToken' )
190 : $request->getVal( 'wpLoginToken' );
191 $this->mReturnTo = $request->getVal( 'returnto', '' );
192 $this->mReturnToQuery = $request->getVal( 'returntoquery', '' );
194 // Show an error or warning passed on from a previous page
195 $entryError = $this->msg( $request->getVal( 'error', '' ) );
196 $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
197 // bc: provide login link as a parameter for messages where the translation
198 // was not updated
199 $loginreqlink = Linker::linkKnown(
200 $this->getPageTitle(),
201 $this->msg( 'loginreqlink' )->escaped(),
202 array(),
203 array(
204 'returnto' => $this->mReturnTo,
205 'returntoquery' => $this->mReturnToQuery,
206 'uselang' => $this->mLanguage,
207 'fromhttp' => $this->mFromHTTP ? '1' : '0',
211 // Only show valid error or warning messages.
212 if ( $entryError->exists()
213 && in_array( $entryError->getKey(), self::getValidErrorMessages() )
215 $this->mEntryErrorType = 'error';
216 $this->mEntryError = $entryError->rawParams( $loginreqlink )->parse();
218 } elseif ( $entryWarning->exists()
219 && in_array( $entryWarning->getKey(), self::getValidErrorMessages() )
221 $this->mEntryErrorType = 'warning';
222 $this->mEntryError = $entryWarning->rawParams( $loginreqlink )->parse();
225 if ( $wgEnableEmail ) {
226 $this->mEmail = $request->getText( 'wpEmail' );
227 } else {
228 $this->mEmail = '';
230 if ( !in_array( 'realname', $wgHiddenPrefs ) ) {
231 $this->mRealName = $request->getText( 'wpRealName' );
232 } else {
233 $this->mRealName = '';
236 if ( !$wgAuth->validDomain( $this->mDomain ) ) {
237 $this->mDomain = $wgAuth->getDomain();
239 $wgAuth->setDomain( $this->mDomain );
241 # 1. When switching accounts, it sucks to get automatically logged out
242 # 2. Do not return to PasswordReset after a successful password change
243 # but goto Wiki start page (Main_Page) instead ( bug 33997 )
244 $returnToTitle = Title::newFromText( $this->mReturnTo );
245 if ( is_object( $returnToTitle )
246 && ( $returnToTitle->isSpecial( 'Userlogout' )
247 || $returnToTitle->isSpecial( 'PasswordReset' ) )
249 $this->mReturnTo = '';
250 $this->mReturnToQuery = '';
254 function getDescription() {
255 if ( $this->mType === 'signup' ) {
256 return $this->msg( 'createaccount' )->text();
257 } else {
258 return $this->msg( 'login' )->text();
263 * @param string|null $subPage
265 public function execute( $subPage ) {
266 if ( session_id() == '' ) {
267 wfSetupSession();
270 $this->load();
272 // Check for [[Special:Userlogin/signup]]. This affects form display and
273 // page title.
274 if ( $subPage == 'signup' ) {
275 $this->mType = 'signup';
277 $this->setHeaders();
280 * In the case where the user is already logged in, and was redirected to
281 * the login form from a page that requires login, do not show the login
282 * page. The use case scenario for this is when a user opens a large number
283 * of tabs, is redirected to the login page on all of them, and then logs
284 * in on one, expecting all the others to work properly.
286 * However, do show the form if it was visited intentionally (no 'returnto'
287 * is present). People who often switch between several accounts have grown
288 * accustomed to this behavior.
290 if (
291 $this->mType !== 'signup' &&
292 !$this->mPosted &&
293 $this->getUser()->isLoggedIn() &&
294 ( $this->mReturnTo !== '' || $this->mReturnToQuery !== '' )
296 $this->successfulLogin();
299 // If logging in and not on HTTPS, either redirect to it or offer a link.
300 global $wgSecureLogin;
301 if ( $this->mRequest->getProtocol() !== 'https' ) {
302 $title = $this->getFullTitle();
303 $query = array(
304 'returnto' => $this->mReturnTo !== '' ? $this->mReturnTo : null,
305 'returntoquery' => $this->mReturnToQuery !== '' ?
306 $this->mReturnToQuery : null,
307 'title' => null,
308 ( $this->mEntryErrorType === 'error' ? 'error' : 'warning' ) => $this->mEntryError,
309 ) + $this->mRequest->getQueryValues();
310 $url = $title->getFullURL( $query, false, PROTO_HTTPS );
311 if ( $wgSecureLogin
312 && wfCanIPUseHTTPS( $this->getRequest()->getIP() )
313 && !$this->mFromHTTP ) // Avoid infinite redirect
315 $url = wfAppendQuery( $url, 'fromhttp=1' );
316 $this->getOutput()->redirect( $url );
317 // Since we only do this redir to change proto, always vary
318 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
320 return;
321 } else {
322 // A wiki without HTTPS login support should set $wgServer to
323 // http://somehost, in which case the secure URL generated
324 // above won't actually start with https://
325 if ( substr( $url, 0, 8 ) === 'https://' ) {
326 $this->mSecureLoginUrl = $url;
331 if ( !is_null( $this->mCookieCheck ) ) {
332 $this->onCookieRedirectCheck( $this->mCookieCheck );
334 return;
335 } elseif ( $this->mPosted ) {
336 if ( $this->mCreateaccount ) {
337 $this->addNewAccount();
339 return;
340 } elseif ( $this->mCreateaccountMail ) {
341 $this->addNewAccountMailPassword();
343 return;
344 } elseif ( ( 'submitlogin' == $this->mAction ) || $this->mLoginattempt ) {
345 $this->processLogin();
347 return;
350 $this->mainLoginForm( $this->mEntryError, $this->mEntryErrorType );
354 * @private
356 function addNewAccountMailPassword() {
357 if ( $this->mEmail == '' ) {
358 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
360 return;
363 $status = $this->addNewAccountInternal();
364 LoggerFactory::getInstance( 'authmanager' )->info(
365 'Account creation attempt with mailed password',
366 array( 'event' => 'accountcreation', 'status' => $status )
368 if ( !$status->isGood() ) {
369 $error = $status->getMessage();
370 $this->mainLoginForm( $error->toString() );
372 return;
375 /** @var User $u */
376 $u = $status->getValue();
378 // Wipe the initial password and mail a temporary one
379 $u->setPassword( null );
380 $u->saveSettings();
381 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
383 Hooks::run( 'AddNewAccount', array( $u, true ) );
384 $u->addNewUserLogEntry( 'byemail', $this->mReason );
386 $out = $this->getOutput();
387 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
389 if ( !$result->isGood() ) {
390 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
391 } else {
392 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
393 $this->executeReturnTo( 'success' );
398 * @private
399 * @return bool
401 function addNewAccount() {
402 global $wgContLang, $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
404 # Create the account and abort if there's a problem doing so
405 $status = $this->addNewAccountInternal();
406 LoggerFactory::getInstance( 'authmanager' )->info( 'Account creation attempt', array(
407 'event' => 'accountcreation',
408 'status' => $status,
409 ) );
411 if ( !$status->isGood() ) {
412 $error = $status->getMessage();
413 $this->mainLoginForm( $error->toString() );
415 return false;
418 $u = $status->getValue();
420 # Only save preferences if the user is not creating an account for someone else.
421 if ( $this->getUser()->isAnon() ) {
422 # If we showed up language selection links, and one was in use, be
423 # smart (and sensible) and save that language as the user's preference
424 if ( $wgLoginLanguageSelector && $this->mLanguage ) {
425 $u->setOption( 'language', $this->mLanguage );
426 } else {
428 # Otherwise the user's language preference defaults to $wgContLang,
429 # but it may be better to set it to their preferred $wgContLang variant,
430 # based on browser preferences or URL parameters.
431 $u->setOption( 'language', $wgContLang->getPreferredVariant() );
433 if ( $wgContLang->hasVariants() ) {
434 $u->setOption( 'variant', $wgContLang->getPreferredVariant() );
438 $out = $this->getOutput();
440 # Send out an email authentication message if needed
441 if ( $wgEmailAuthentication && Sanitizer::validateEmail( $u->getEmail() ) ) {
442 $status = $u->sendConfirmationMail();
443 if ( $status->isGood() ) {
444 $out->addWikiMsg( 'confirmemail_oncreate' );
445 } else {
446 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
450 # Save settings (including confirmation token)
451 $u->saveSettings();
453 # If not logged in, assume the new account as the current one and set
454 # session cookies then show a "welcome" message or a "need cookies"
455 # message as needed
456 if ( $this->getUser()->isAnon() ) {
457 $u->setCookies();
458 $wgUser = $u;
459 // This should set it for OutputPage and the Skin
460 // which is needed or the personal links will be
461 // wrong.
462 $this->getContext()->setUser( $u );
463 Hooks::run( 'AddNewAccount', array( $u, false ) );
464 $u->addNewUserLogEntry( 'create' );
465 if ( $this->hasSessionCookie() ) {
466 $this->successfulCreation();
467 } else {
468 $this->cookieRedirectCheck( 'new' );
470 } else {
471 # Confirm that the account was created
472 $out->setPageTitle( $this->msg( 'accountcreated' ) );
473 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
474 $out->addReturnTo( $this->getPageTitle() );
475 Hooks::run( 'AddNewAccount', array( $u, false ) );
476 $u->addNewUserLogEntry( 'create2', $this->mReason );
479 return true;
483 * Make a new user account using the loaded data.
484 * @private
485 * @throws PermissionsError|ReadOnlyError
486 * @return Status
488 public function addNewAccountInternal() {
489 global $wgAuth, $wgAccountCreationThrottle, $wgEmailConfirmToEdit;
491 // If the user passes an invalid domain, something is fishy
492 if ( !$wgAuth->validDomain( $this->mDomain ) ) {
493 return Status::newFatal( 'wrongpassword' );
496 // If we are not allowing users to login locally, we should be checking
497 // to see if the user is actually able to authenticate to the authenti-
498 // cation server before they create an account (otherwise, they can
499 // create a local account and login as any domain user). We only need
500 // to check this for domains that aren't local.
501 if ( 'local' != $this->mDomain && $this->mDomain != '' ) {
502 if (
503 !$wgAuth->canCreateAccounts() &&
505 !$wgAuth->userExists( $this->mUsername ) ||
506 !$wgAuth->authenticate( $this->mUsername, $this->mPassword )
509 return Status::newFatal( 'wrongpassword' );
513 if ( wfReadOnly() ) {
514 throw new ReadOnlyError;
517 # Request forgery checks.
518 if ( !self::getCreateaccountToken() ) {
519 self::setCreateaccountToken();
521 return Status::newFatal( 'nocookiesfornew' );
524 # The user didn't pass a createaccount token
525 if ( !$this->mToken ) {
526 return Status::newFatal( 'sessionfailure' );
529 # Validate the createaccount token
530 if ( $this->mToken !== self::getCreateaccountToken() ) {
531 return Status::newFatal( 'sessionfailure' );
534 # Check permissions
535 $currentUser = $this->getUser();
536 $creationBlock = $currentUser->isBlockedFromCreateAccount();
537 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
538 throw new PermissionsError( 'createaccount' );
539 } elseif ( $creationBlock instanceof Block ) {
540 // Throws an ErrorPageError.
541 $this->userBlockedMessage( $creationBlock );
543 // This should never be reached.
544 return false;
547 # Include checks that will include GlobalBlocking (Bug 38333)
548 $permErrors = $this->getPageTitle()->getUserPermissionsErrors(
549 'createaccount',
550 $currentUser,
551 true
554 if ( count( $permErrors ) ) {
555 throw new PermissionsError( 'createaccount', $permErrors );
558 $ip = $this->getRequest()->getIP();
559 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
560 return Status::newFatal( 'sorbs_create_account_reason' );
563 # Now create a dummy user ($u) and check if it is valid
564 $u = User::newFromName( $this->mUsername, 'creatable' );
565 if ( !$u ) {
566 return Status::newFatal( 'noname' );
569 $cache = ObjectCache::getLocalClusterInstance();
570 # Make sure the user does not exist already
571 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $this->mUsername ) ) );
572 if ( !$lock ) {
573 return Status::newFatal( 'usernameinprogress' );
574 } elseif ( $u->idForName( User::READ_LOCKING ) ) {
575 return Status::newFatal( 'userexists' );
578 if ( $this->mCreateaccountMail ) {
579 # do not force a password for account creation by email
580 # set invalid password, it will be replaced later by a random generated password
581 $this->mPassword = null;
582 } else {
583 if ( $this->mPassword !== $this->mRetype ) {
584 return Status::newFatal( 'badretype' );
587 # check for password validity, return a fatal Status if invalid
588 $validity = $u->checkPasswordValidity( $this->mPassword, 'create' );
589 if ( !$validity->isGood() ) {
590 $validity->ok = false; // make sure this Status is fatal
591 return $validity;
595 # if you need a confirmed email address to edit, then obviously you
596 # need an email address.
597 if ( $wgEmailConfirmToEdit && strval( $this->mEmail ) === '' ) {
598 return Status::newFatal( 'noemailtitle' );
601 if ( strval( $this->mEmail ) !== '' && !Sanitizer::validateEmail( $this->mEmail ) ) {
602 return Status::newFatal( 'invalidemailaddress' );
605 # Set some additional data so the AbortNewAccount hook can be used for
606 # more than just username validation
607 $u->setEmail( $this->mEmail );
608 $u->setRealName( $this->mRealName );
610 $abortError = '';
611 $abortStatus = null;
612 if ( !Hooks::run( 'AbortNewAccount', array( $u, &$abortError, &$abortStatus ) ) ) {
613 // Hook point to add extra creation throttles and blocks
614 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
615 if ( $abortStatus === null ) {
616 // Report back the old string as a raw message status.
617 // This will report the error back as 'createaccount-hook-aborted'
618 // with the given string as the message.
619 // To return a different error code, return a Status object.
620 $abortError = new Message( 'createaccount-hook-aborted', array( $abortError ) );
621 $abortError->text();
623 return Status::newFatal( $abortError );
624 } else {
625 // For MediaWiki 1.23+ and updated hooks, return the Status object
626 // returned from the hook.
627 return $abortStatus;
631 // Hook point to check for exempt from account creation throttle
632 if ( !Hooks::run( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
633 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook " .
634 "allowed account creation w/o throttle\n" );
635 } else {
636 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
637 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
638 $value = $cache->get( $key );
639 if ( !$value ) {
640 $cache->set( $key, 0, $cache::TTL_DAY );
642 if ( $value >= $wgAccountCreationThrottle ) {
643 return Status::newFatal( 'acct_creation_throttle_hit', $wgAccountCreationThrottle );
645 $cache->incr( $key );
649 if ( !$wgAuth->addUser( $u, $this->mPassword, $this->mEmail, $this->mRealName ) ) {
650 return Status::newFatal( 'externaldberror' );
653 self::clearCreateaccountToken();
655 return $this->initUser( $u, false );
659 * Actually add a user to the database.
660 * Give it a User object that has been initialised with a name.
662 * @param User $u
663 * @param bool $autocreate True if this is an autocreation via auth plugin
664 * @return Status Status object, with the User object in the value member on success
665 * @private
667 function initUser( $u, $autocreate ) {
668 global $wgAuth;
670 $status = $u->addToDatabase();
671 if ( !$status->isOK() ) {
672 return $status;
675 if ( $wgAuth->allowPasswordChange() ) {
676 $u->setPassword( $this->mPassword );
679 $u->setEmail( $this->mEmail );
680 $u->setRealName( $this->mRealName );
681 $u->setToken();
683 Hooks::run( 'LocalUserCreated', array( $u, $autocreate ) );
684 $oldUser = $u;
685 $wgAuth->initUser( $u, $autocreate );
686 if ( $oldUser !== $u ) {
687 wfWarn( get_class( $wgAuth ) . '::initUser() replaced the user object' );
690 $u->saveSettings();
692 // Update user count
693 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
695 // Watch user's userpage and talk page
696 $u->addWatch( $u->getUserPage(), WatchedItem::IGNORE_USER_RIGHTS );
698 return Status::newGood( $u );
702 * Internally authenticate the login request.
704 * This may create a local account as a side effect if the
705 * authentication plugin allows transparent local account
706 * creation.
707 * @return int
709 public function authenticateUserData() {
710 global $wgUser, $wgAuth;
712 $this->load();
714 if ( $this->mUsername == '' ) {
715 return self::NO_NAME;
718 // We require a login token to prevent login CSRF
719 // Handle part of this before incrementing the throttle so
720 // token-less login attempts don't count towards the throttle
721 // but wrong-token attempts do.
723 // If the user doesn't have a login token yet, set one.
724 if ( !self::getLoginToken() ) {
725 self::setLoginToken();
727 return self::NEED_TOKEN;
729 // If the user didn't pass a login token, tell them we need one
730 if ( !$this->mToken ) {
731 return self::NEED_TOKEN;
734 $throttleCount = self::incLoginThrottle( $this->mUsername );
735 if ( $throttleCount === true ) {
736 return self::THROTTLED;
739 // Validate the login token
740 if ( $this->mToken !== self::getLoginToken() ) {
741 return self::WRONG_TOKEN;
744 // Load the current user now, and check to see if we're logging in as
745 // the same name. This is necessary because loading the current user
746 // (say by calling getName()) calls the UserLoadFromSession hook, which
747 // potentially creates the user in the database. Until we load $wgUser,
748 // checking for user existence using User::newFromName($name)->getId() below
749 // will effectively be using stale data.
750 if ( $this->getUser()->getName() === $this->mUsername ) {
751 wfDebug( __METHOD__ . ": already logged in as {$this->mUsername}\n" );
753 return self::SUCCESS;
756 $u = User::newFromName( $this->mUsername );
757 if ( $u === false ) {
758 return self::ILLEGAL;
761 $msg = null;
762 // Give extensions a way to indicate the username has been updated,
763 // rather than telling the user the account doesn't exist.
764 if ( !Hooks::run( 'LoginUserMigrated', array( $u, &$msg ) ) ) {
765 $this->mAbortLoginErrorMsg = $msg;
766 return self::USER_MIGRATED;
769 if ( !User::isUsableName( $u->getName() ) ) {
770 return self::ILLEGAL;
773 $isAutoCreated = false;
774 if ( $u->getID() == 0 ) {
775 $status = $this->attemptAutoCreate( $u );
776 if ( $status !== self::SUCCESS ) {
777 return $status;
778 } else {
779 $isAutoCreated = true;
781 } else {
782 $u->load();
785 // Give general extensions, such as a captcha, a chance to abort logins
786 $abort = self::ABORTED;
787 if ( !Hooks::run( 'AbortLogin', array( $u, $this->mPassword, &$abort, &$msg ) ) ) {
788 if ( !in_array( $abort, array_keys( self::$statusCodes ), true ) ) {
789 throw new Exception( 'Invalid status code returned from AbortLogin hook: ' . $abort );
791 $this->mAbortLoginErrorMsg = $msg;
792 return $abort;
795 global $wgBlockDisablesLogin;
796 if ( !$u->checkPassword( $this->mPassword ) ) {
797 if ( $u->checkTemporaryPassword( $this->mPassword ) ) {
799 * The e-mailed temporary password should not be used for actu-
800 * al logins; that's a very sloppy habit, and insecure if an
801 * attacker has a few seconds to click "search" on someone's
802 * open mail reader.
804 * Allow it to be used only to reset the password a single time
805 * to a new value, which won't be in the user's e-mail ar-
806 * chives.
808 * For backwards compatibility, we'll still recognize it at the
809 * login form to minimize surprises for people who have been
810 * logging in with a temporary password for some time.
812 * As a side-effect, we can authenticate the user's e-mail ad-
813 * dress if it's not already done, since the temporary password
814 * was sent via e-mail.
816 if ( !$u->isEmailConfirmed() && !wfReadOnly() ) {
817 $u->confirmEmail();
818 $u->saveSettings();
821 // At this point we just return an appropriate code/ indicating
822 // that the UI should show a password reset form; bot inter-
823 // faces etc will probably just fail cleanly here.
824 $this->mAbortLoginErrorMsg = 'resetpass-temp-emailed';
825 $this->mTempPasswordUsed = true;
826 $retval = self::RESET_PASS;
827 } else {
828 $retval = ( $this->mPassword == '' ) ? self::EMPTY_PASS : self::WRONG_PASS;
830 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
831 // If we've enabled it, make it so that a blocked user cannot login
832 $retval = self::USER_BLOCKED;
833 } elseif ( $this->checkUserPasswordExpired( $u ) == 'hard' ) {
834 // Force reset now, without logging in
835 $retval = self::RESET_PASS;
836 $this->mAbortLoginErrorMsg = 'resetpass-expired';
837 } else {
838 Hooks::run( 'UserLoggedIn', array( $u ) );
839 $oldUser = $u;
840 $wgAuth->updateUser( $u );
841 if ( $oldUser !== $u ) {
842 wfWarn( get_class( $wgAuth ) . '::updateUser() replaced the user object' );
844 $wgUser = $u;
845 // This should set it for OutputPage and the Skin
846 // which is needed or the personal links will be
847 // wrong.
848 $this->getContext()->setUser( $u );
850 // Please reset throttle for successful logins, thanks!
851 if ( $throttleCount ) {
852 self::clearLoginThrottle( $this->mUsername );
855 if ( $isAutoCreated ) {
856 // Must be run after $wgUser is set, for correct new user log
857 Hooks::run( 'AuthPluginAutoCreate', array( $u ) );
860 $retval = self::SUCCESS;
862 Hooks::run( 'LoginAuthenticateAudit', array( $u, $this->mPassword, $retval ) );
864 return $retval;
868 * Increment the login attempt throttle hit count for the (username,current IP)
869 * tuple unless the throttle was already reached.
870 * @param string $username The user name
871 * @return bool|int The integer hit count or True if it is already at the limit
873 public static function incLoginThrottle( $username ) {
874 global $wgPasswordAttemptThrottle, $wgRequest;
875 $username = trim( $username ); // sanity
877 $throttleCount = 0;
878 if ( is_array( $wgPasswordAttemptThrottle ) ) {
879 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
880 $count = $wgPasswordAttemptThrottle['count'];
881 $period = $wgPasswordAttemptThrottle['seconds'];
883 $cache = ObjectCache::getLocalClusterInstance();
884 $throttleCount = $cache->get( $throttleKey );
885 if ( !$throttleCount ) {
886 $cache->add( $throttleKey, 1, $period ); // start counter
887 } elseif ( $throttleCount < $count ) {
888 $cache->incr( $throttleKey );
889 } elseif ( $throttleCount >= $count ) {
890 return true;
894 return $throttleCount;
898 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
899 * @param string $username The user name
900 * @return void
902 public static function clearLoginThrottle( $username ) {
903 global $wgRequest;
904 $username = trim( $username ); // sanity
906 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
907 ObjectCache::getLocalClusterInstance()->delete( $throttleKey );
911 * Attempt to automatically create a user on login. Only succeeds if there
912 * is an external authentication method which allows it.
914 * @param User $user
916 * @return int Status code
918 function attemptAutoCreate( $user ) {
919 global $wgAuth;
921 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
922 wfDebug( __METHOD__ . ": user is blocked from account creation\n" );
924 return self::CREATE_BLOCKED;
927 if ( !$wgAuth->autoCreate() ) {
928 return self::NOT_EXISTS;
931 if ( !$wgAuth->userExists( $user->getName() ) ) {
932 wfDebug( __METHOD__ . ": user does not exist\n" );
934 return self::NOT_EXISTS;
937 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword ) ) {
938 wfDebug( __METHOD__ . ": \$wgAuth->authenticate() returned false, aborting\n" );
940 return self::WRONG_PLUGIN_PASS;
943 $abortError = '';
944 if ( !Hooks::run( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
945 // Hook point to add extra creation throttles and blocks
946 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
947 $this->mAbortLoginErrorMsg = $abortError;
949 return self::ABORTED;
952 wfDebug( __METHOD__ . ": creating account\n" );
953 $status = $this->initUser( $user, true );
955 if ( !$status->isOK() ) {
956 $errors = $status->getErrorsByType( 'error' );
957 $this->mAbortLoginErrorMsg = $errors[0]['message'];
959 return self::ABORTED;
962 return self::SUCCESS;
965 function processLogin() {
966 global $wgLang, $wgSecureLogin, $wgPasswordAttemptThrottle, $wgInvalidPasswordReset;
968 $cache = ObjectCache::getLocalClusterInstance();
969 $authRes = $this->authenticateUserData();
970 switch ( $authRes ) {
971 case self::SUCCESS:
972 # We've verified now, update the real record
973 $user = $this->getUser();
974 $user->touch();
976 if ( $user->requiresHTTPS() ) {
977 $this->mStickHTTPS = true;
980 if ( $wgSecureLogin && !$this->mStickHTTPS ) {
981 $user->setCookies( $this->mRequest, false, $this->mRemember );
982 } else {
983 $user->setCookies( $this->mRequest, null, $this->mRemember );
985 self::clearLoginToken();
987 // Reset the throttle
988 $request = $this->getRequest();
989 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername ) );
990 $cache->delete( $key );
992 if ( $this->hasSessionCookie() || $this->mSkipCookieCheck ) {
993 /* Replace the language object to provide user interface in
994 * correct language immediately on this first page load.
996 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
997 $userLang = Language::factory( $code );
998 $wgLang = $userLang;
999 $this->getContext()->setLanguage( $userLang );
1000 // Reset SessionID on Successful login (bug 40995)
1001 $this->renewSessionId();
1002 if ( $this->checkUserPasswordExpired( $this->getUser() ) == 'soft' ) {
1003 $this->resetLoginForm( $this->msg( 'resetpass-expired-soft' ) );
1004 } elseif ( $wgInvalidPasswordReset
1005 && !$user->isValidPassword( $this->mPassword )
1007 $status = $user->checkPasswordValidity(
1008 $this->mPassword,
1009 'login'
1011 $this->resetLoginForm(
1012 $status->getMessage( 'resetpass-validity-soft' )
1014 } else {
1015 $this->successfulLogin();
1017 } else {
1018 $this->cookieRedirectCheck( 'login' );
1020 break;
1022 case self::NEED_TOKEN:
1023 $error = $this->mAbortLoginErrorMsg ?: 'nocookiesforlogin';
1024 $this->mainLoginForm( $this->msg( $error )->parse() );
1025 break;
1026 case self::WRONG_TOKEN:
1027 $error = $this->mAbortLoginErrorMsg ?: 'sessionfailure';
1028 $this->mainLoginForm( $this->msg( $error )->text() );
1029 break;
1030 case self::NO_NAME:
1031 case self::ILLEGAL:
1032 $error = $this->mAbortLoginErrorMsg ?: 'noname';
1033 $this->mainLoginForm( $this->msg( $error )->text() );
1034 break;
1035 case self::WRONG_PLUGIN_PASS:
1036 $error = $this->mAbortLoginErrorMsg ?: 'wrongpassword';
1037 $this->mainLoginForm( $this->msg( $error )->text() );
1038 break;
1039 case self::NOT_EXISTS:
1040 if ( $this->getUser()->isAllowed( 'createaccount' ) ) {
1041 $error = $this->mAbortLoginErrorMsg ?: 'nosuchuser';
1042 $this->mainLoginForm( $this->msg( $error,
1043 wfEscapeWikiText( $this->mUsername ) )->parse() );
1044 } else {
1045 $error = $this->mAbortLoginErrorMsg ?: 'nosuchusershort';
1046 $this->mainLoginForm( $this->msg( $error,
1047 wfEscapeWikiText( $this->mUsername ) )->text() );
1049 break;
1050 case self::WRONG_PASS:
1051 $error = $this->mAbortLoginErrorMsg ?: 'wrongpassword';
1052 $this->mainLoginForm( $this->msg( $error )->text() );
1053 break;
1054 case self::EMPTY_PASS:
1055 $error = $this->mAbortLoginErrorMsg ?: 'wrongpasswordempty';
1056 $this->mainLoginForm( $this->msg( $error )->text() );
1057 break;
1058 case self::RESET_PASS:
1059 $error = $this->mAbortLoginErrorMsg ?: 'resetpass_announce';
1060 $this->resetLoginForm( $this->msg( $error ) );
1061 break;
1062 case self::CREATE_BLOCKED:
1063 $this->userBlockedMessage( $this->getUser()->isBlockedFromCreateAccount() );
1064 break;
1065 case self::THROTTLED:
1066 $error = $this->mAbortLoginErrorMsg ?: 'login-throttled';
1067 $this->mainLoginForm( $this->msg( $error )
1068 ->params( $this->getLanguage()->formatDuration( $wgPasswordAttemptThrottle['seconds'] ) )
1069 ->text()
1071 break;
1072 case self::USER_BLOCKED:
1073 $error = $this->mAbortLoginErrorMsg ?: 'login-userblocked';
1074 $this->mainLoginForm( $this->msg( $error, $this->mUsername )->escaped() );
1075 break;
1076 case self::ABORTED:
1077 $error = $this->mAbortLoginErrorMsg ?: 'login-abort-generic';
1078 $this->mainLoginForm( $this->msg( $error,
1079 wfEscapeWikiText( $this->mUsername ) )->text() );
1080 break;
1081 case self::USER_MIGRATED:
1082 $error = $this->mAbortLoginErrorMsg ?: 'login-migrated-generic';
1083 $params = array();
1084 if ( is_array( $error ) ) {
1085 $error = array_shift( $this->mAbortLoginErrorMsg );
1086 $params = $this->mAbortLoginErrorMsg;
1088 $this->mainLoginForm( $this->msg( $error, $params )->text() );
1089 break;
1090 default:
1091 throw new MWException( 'Unhandled case value' );
1094 LoggerFactory::getInstance( 'authmanager' )->info( 'Login attempt', array(
1095 'event' => 'login',
1096 'successful' => $authRes === self::SUCCESS,
1097 'status' => LoginForm::$statusCodes[$authRes],
1098 ) );
1102 * Show the Special:ChangePassword form, with custom message
1103 * @param Message $msg
1105 protected function resetLoginForm( Message $msg ) {
1106 // Allow hooks to explain this password reset in more detail
1107 Hooks::run( 'LoginPasswordResetMessage', array( &$msg, $this->mUsername ) );
1108 $reset = new SpecialChangePassword();
1109 $derivative = new DerivativeContext( $this->getContext() );
1110 $derivative->setTitle( $reset->getPageTitle() );
1111 $reset->setContext( $derivative );
1112 if ( !$this->mTempPasswordUsed ) {
1113 $reset->setOldPasswordMessage( 'oldpassword' );
1115 $reset->setChangeMessage( $msg );
1116 $reset->execute( null );
1120 * @param User $u
1121 * @param bool $throttle
1122 * @param string $emailTitle Message name of email title
1123 * @param string $emailText Message name of email text
1124 * @return Status
1126 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle',
1127 $emailText = 'passwordremindertext'
1129 global $wgNewPasswordExpiry, $wgMinimalPasswordLength;
1131 if ( $u->getEmail() == '' ) {
1132 return Status::newFatal( 'noemail', $u->getName() );
1134 $ip = $this->getRequest()->getIP();
1135 if ( !$ip ) {
1136 return Status::newFatal( 'badipaddress' );
1139 $currentUser = $this->getUser();
1140 Hooks::run( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
1142 $np = PasswordFactory::generateRandomPasswordString( $wgMinimalPasswordLength );
1143 $u->setNewpassword( $np, $throttle );
1144 $u->saveSettings();
1145 $userLanguage = $u->getOption( 'language' );
1147 $mainPage = Title::newMainPage();
1148 $mainPageUrl = $mainPage->getCanonicalURL();
1150 $m = $this->msg( $emailText, $ip, $u->getName(), $np, '<' . $mainPageUrl . '>',
1151 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
1152 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
1154 return $result;
1158 * Run any hooks registered for logins, then HTTP redirect to
1159 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
1160 * nice message here, but that's really not as useful as just being sent to
1161 * wherever you logged in from. It should be clear that the action was
1162 * successful, given the lack of error messages plus the appearance of your
1163 * name in the upper right.
1165 * @private
1167 function successfulLogin() {
1168 # Run any hooks; display injected HTML if any, else redirect
1169 $currentUser = $this->getUser();
1170 $injected_html = '';
1171 Hooks::run( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
1173 if ( $injected_html !== '' ) {
1174 $this->displaySuccessfulAction( 'success', $this->msg( 'loginsuccesstitle' ),
1175 'loginsuccess', $injected_html );
1176 } else {
1177 $this->executeReturnTo( 'successredirect' );
1182 * Run any hooks registered for logins, then display a message welcoming
1183 * the user.
1185 * @private
1187 function successfulCreation() {
1188 # Run any hooks; display injected HTML
1189 $currentUser = $this->getUser();
1190 $injected_html = '';
1191 $welcome_creation_msg = 'welcomecreation-msg';
1193 Hooks::run( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
1196 * Let any extensions change what message is shown.
1197 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
1198 * @since 1.18
1200 Hooks::run( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
1202 $this->displaySuccessfulAction(
1203 'signup',
1204 $this->msg( 'welcomeuser', $this->getUser()->getName() ),
1205 $welcome_creation_msg, $injected_html
1210 * Display a "successful action" page.
1212 * @param string $type Condition of return to; see `executeReturnTo`
1213 * @param string|Message $title Page's title
1214 * @param string $msgname
1215 * @param string $injected_html
1217 private function displaySuccessfulAction( $type, $title, $msgname, $injected_html ) {
1218 $out = $this->getOutput();
1219 $out->setPageTitle( $title );
1220 if ( $msgname ) {
1221 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
1224 $out->addHTML( $injected_html );
1226 $this->executeReturnTo( $type );
1230 * Output a message that informs the user that they cannot create an account because
1231 * there is a block on them or their IP which prevents account creation. Note that
1232 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
1233 * setting on blocks (bug 13611).
1234 * @param Block $block The block causing this error
1235 * @throws ErrorPageError
1237 function userBlockedMessage( Block $block ) {
1238 # Let's be nice about this, it's likely that this feature will be used
1239 # for blocking large numbers of innocent people, e.g. range blocks on
1240 # schools. Don't blame it on the user. There's a small chance that it
1241 # really is the user's fault, i.e. the username is blocked and they
1242 # haven't bothered to log out before trying to create an account to
1243 # evade it, but we'll leave that to their guilty conscience to figure
1244 # out.
1245 $errorParams = array(
1246 $block->getTarget(),
1247 $block->mReason ? $block->mReason : $this->msg( 'blockednoreason' )->text(),
1248 $block->getByName()
1251 if ( $block->getType() === Block::TYPE_RANGE ) {
1252 $errorMessage = 'cantcreateaccount-range-text';
1253 $errorParams[] = $this->getRequest()->getIP();
1254 } else {
1255 $errorMessage = 'cantcreateaccount-text';
1258 throw new ErrorPageError(
1259 'cantcreateaccounttitle',
1260 $errorMessage,
1261 $errorParams
1266 * Add a "return to" link or redirect to it.
1267 * Extensions can use this to reuse the "return to" logic after
1268 * inject steps (such as redirection) into the login process.
1270 * @param string $type One of the following:
1271 * - error: display a return to link ignoring $wgRedirectOnLogin
1272 * - signup: display a return to link using $wgRedirectOnLogin if needed
1273 * - success: display a return to link using $wgRedirectOnLogin if needed
1274 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1275 * @param string $returnTo
1276 * @param array|string $returnToQuery
1277 * @param bool $stickHTTPs Keep redirect link on HTTPs
1278 * @since 1.22
1280 public function showReturnToPage(
1281 $type, $returnTo = '', $returnToQuery = '', $stickHTTPs = false
1283 $this->mReturnTo = $returnTo;
1284 $this->mReturnToQuery = $returnToQuery;
1285 $this->mStickHTTPS = $stickHTTPs;
1286 $this->executeReturnTo( $type );
1290 * Add a "return to" link or redirect to it.
1292 * @param string $type One of the following:
1293 * - error: display a return to link ignoring $wgRedirectOnLogin
1294 * - signup: display a return to link using $wgRedirectOnLogin if needed
1295 * - success: display a return to link using $wgRedirectOnLogin if needed
1296 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1298 private function executeReturnTo( $type ) {
1299 global $wgRedirectOnLogin, $wgSecureLogin;
1301 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
1302 $returnTo = $wgRedirectOnLogin;
1303 $returnToQuery = array();
1304 } else {
1305 $returnTo = $this->mReturnTo;
1306 $returnToQuery = wfCgiToArray( $this->mReturnToQuery );
1309 // Allow modification of redirect behavior
1310 Hooks::run( 'PostLoginRedirect', array( &$returnTo, &$returnToQuery, &$type ) );
1312 $returnToTitle = Title::newFromText( $returnTo );
1313 if ( !$returnToTitle ) {
1314 $returnToTitle = Title::newMainPage();
1317 if ( $wgSecureLogin && !$this->mStickHTTPS ) {
1318 $options = array( 'http' );
1319 $proto = PROTO_HTTP;
1320 } elseif ( $wgSecureLogin ) {
1321 $options = array( 'https' );
1322 $proto = PROTO_HTTPS;
1323 } else {
1324 $options = array();
1325 $proto = PROTO_RELATIVE;
1328 if ( $type == 'successredirect' ) {
1329 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery, false, $proto );
1330 $this->getOutput()->redirect( $redirectUrl );
1331 } else {
1332 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery, null, $options );
1337 * @param string $msg
1338 * @param string $msgtype
1339 * @throws ErrorPageError
1340 * @throws Exception
1341 * @throws FatalError
1342 * @throws MWException
1343 * @throws PermissionsError
1344 * @throws ReadOnlyError
1345 * @private
1347 function mainLoginForm( $msg, $msgtype = 'error' ) {
1348 global $wgEnableEmail, $wgEnableUserEmail;
1349 global $wgHiddenPrefs, $wgLoginLanguageSelector;
1350 global $wgAuth, $wgEmailConfirmToEdit;
1351 global $wgSecureLogin, $wgPasswordResetRoutes;
1352 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
1354 $titleObj = $this->getPageTitle();
1355 $user = $this->getUser();
1356 $out = $this->getOutput();
1358 if ( $this->mType == 'signup' ) {
1359 // Block signup here if in readonly. Keeps user from
1360 // going through the process (filling out data, etc)
1361 // and being informed later.
1362 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
1363 if ( count( $permErrors ) ) {
1364 throw new PermissionsError( 'createaccount', $permErrors );
1365 } elseif ( $user->isBlockedFromCreateAccount() ) {
1366 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1368 return;
1369 } elseif ( wfReadOnly() ) {
1370 throw new ReadOnlyError;
1374 // Pre-fill username (if not creating an account, bug 44775).
1375 if ( $this->mUsername == '' && $this->mType != 'signup' ) {
1376 if ( $user->isLoggedIn() ) {
1377 $this->mUsername = $user->getName();
1378 } else {
1379 $this->mUsername = $this->getRequest()->getCookie( 'UserName' );
1383 // Generic styles and scripts for both login and signup form
1384 $out->addModuleStyles( array(
1385 'mediawiki.ui',
1386 'mediawiki.ui.button',
1387 'mediawiki.ui.checkbox',
1388 'mediawiki.ui.input',
1389 'mediawiki.special.userlogin.common.styles'
1390 ) );
1392 if ( $this->mType == 'signup' ) {
1393 // Additional styles and scripts for signup form
1394 $out->addModules( array(
1395 'mediawiki.special.userlogin.signup.js'
1396 ) );
1397 $out->addModuleStyles( array(
1398 'mediawiki.special.userlogin.signup.styles'
1399 ) );
1401 $template = new UsercreateTemplate( $this->getConfig() );
1403 // Must match number of benefits defined in messages
1404 $template->set( 'benefitCount', 3 );
1406 $q = 'action=submitlogin&type=signup';
1407 $linkq = 'type=login';
1408 } else {
1409 // Additional styles for login form
1410 $out->addModuleStyles( array(
1411 'mediawiki.special.userlogin.login.styles'
1412 ) );
1414 $template = new UserloginTemplate( $this->getConfig() );
1416 $q = 'action=submitlogin&type=login';
1417 $linkq = 'type=signup';
1420 if ( $this->mReturnTo !== '' ) {
1421 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
1422 if ( $this->mReturnToQuery !== '' ) {
1423 $returnto .= '&returntoquery=' .
1424 wfUrlencode( $this->mReturnToQuery );
1426 $q .= $returnto;
1427 $linkq .= $returnto;
1430 # Don't show a "create account" link if the user can't.
1431 if ( $this->showCreateOrLoginLink( $user ) ) {
1432 # Pass any language selection on to the mode switch link
1433 if ( $wgLoginLanguageSelector && $this->mLanguage ) {
1434 $linkq .= '&uselang=' . $this->mLanguage;
1436 // Supply URL, login template creates the button.
1437 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
1438 } else {
1439 $template->set( 'link', '' );
1442 $resetLink = $this->mType == 'signup'
1443 ? null
1444 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1446 $template->set( 'header', '' );
1447 $template->set( 'formheader', '' );
1448 $template->set( 'skin', $this->getSkin() );
1449 $template->set( 'name', $this->mUsername );
1450 $template->set( 'password', $this->mPassword );
1451 $template->set( 'retype', $this->mRetype );
1452 $template->set( 'createemailset', $this->mCreateaccountMail );
1453 $template->set( 'email', $this->mEmail );
1454 $template->set( 'realname', $this->mRealName );
1455 $template->set( 'domain', $this->mDomain );
1456 $template->set( 'reason', $this->mReason );
1458 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1459 $template->set( 'message', $msg );
1460 $template->set( 'messagetype', $msgtype );
1461 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1462 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1463 $template->set( 'useemail', $wgEnableEmail );
1464 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1465 $template->set( 'emailothers', $wgEnableUserEmail );
1466 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1467 $template->set( 'resetlink', $resetLink );
1468 $template->set( 'canremember', $wgExtendedLoginCookieExpiration === null ?
1469 ( $wgCookieExpiration > 0 ) :
1470 ( $wgExtendedLoginCookieExpiration > 0 ) );
1471 $template->set( 'usereason', $user->isLoggedIn() );
1472 $template->set( 'remember', $this->mRemember );
1473 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1474 $template->set( 'stickhttps', (int)$this->mStickHTTPS );
1475 $template->set( 'loggedin', $user->isLoggedIn() );
1476 $template->set( 'loggedinuser', $user->getName() );
1478 if ( $this->mType == 'signup' ) {
1479 if ( !self::getCreateaccountToken() ) {
1480 self::setCreateaccountToken();
1482 $template->set( 'token', self::getCreateaccountToken() );
1483 } else {
1484 if ( !self::getLoginToken() ) {
1485 self::setLoginToken();
1487 $template->set( 'token', self::getLoginToken() );
1490 # Prepare language selection links as needed
1491 if ( $wgLoginLanguageSelector ) {
1492 $template->set( 'languages', $this->makeLanguageSelector() );
1493 if ( $this->mLanguage ) {
1494 $template->set( 'uselang', $this->mLanguage );
1498 $template->set( 'secureLoginUrl', $this->mSecureLoginUrl );
1499 // Use signupend-https for HTTPS requests if it's not blank, signupend otherwise
1500 $usingHTTPS = $this->mRequest->getProtocol() == 'https';
1501 $signupendHTTPS = $this->msg( 'signupend-https' );
1502 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1503 $template->set( 'signupend', $signupendHTTPS->parse() );
1504 } else {
1505 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1508 // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
1509 if ( $usingHTTPS ) {
1510 $template->set( 'fromhttp', $this->mFromHTTP );
1513 // Give authentication and captcha plugins a chance to modify the form
1514 $wgAuth->modifyUITemplate( $template, $this->mType );
1515 if ( $this->mType == 'signup' ) {
1516 Hooks::run( 'UserCreateForm', array( &$template ) );
1517 } else {
1518 Hooks::run( 'UserLoginForm', array( &$template ) );
1521 $out->disallowUserJs(); // just in case...
1522 $out->addTemplate( $template );
1526 * Whether the login/create account form should display a link to the
1527 * other form (in addition to whatever the skin provides).
1529 * @param User $user
1530 * @return bool
1532 private function showCreateOrLoginLink( &$user ) {
1533 if ( $this->mType == 'signup' ) {
1534 return true;
1535 } elseif ( $user->isAllowed( 'createaccount' ) ) {
1536 return true;
1537 } else {
1538 return false;
1543 * Check if a session cookie is present.
1545 * This will not pick up a cookie set during _this_ request, but is meant
1546 * to ensure that the client is returning the cookie which was set on a
1547 * previous pass through the system.
1549 * @private
1550 * @return bool
1552 function hasSessionCookie() {
1553 global $wgDisableCookieCheck;
1555 return $wgDisableCookieCheck ? true : $this->getRequest()->checkSessionCookie();
1559 * Get the login token from the current session
1560 * @return mixed
1562 public static function getLoginToken() {
1563 global $wgRequest;
1565 return $wgRequest->getSessionData( 'wsLoginToken' );
1569 * Randomly generate a new login token and attach it to the current session
1571 public static function setLoginToken() {
1572 global $wgRequest;
1573 // Generate a token directly instead of using $user->getEditToken()
1574 // because the latter reuses $_SESSION['wsEditToken']
1575 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand::generateHex( 32 ) );
1579 * Remove any login token attached to the current session
1581 public static function clearLoginToken() {
1582 global $wgRequest;
1583 $wgRequest->setSessionData( 'wsLoginToken', null );
1587 * Get the createaccount token from the current session
1588 * @return mixed
1590 public static function getCreateaccountToken() {
1591 global $wgRequest;
1592 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1596 * Randomly generate a new createaccount token and attach it to the current session
1598 public static function setCreateaccountToken() {
1599 global $wgRequest;
1600 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand::generateHex( 32 ) );
1604 * Remove any createaccount token attached to the current session
1606 public static function clearCreateaccountToken() {
1607 global $wgRequest;
1608 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1612 * Renew the user's session id, using strong entropy
1614 private function renewSessionId() {
1615 global $wgSecureLogin, $wgCookieSecure;
1616 if ( $wgSecureLogin && !$this->mStickHTTPS ) {
1617 $wgCookieSecure = false;
1620 wfResetSessionID();
1624 * @param string $type
1625 * @private
1627 function cookieRedirectCheck( $type ) {
1628 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
1629 $query = array( 'wpCookieCheck' => $type );
1630 if ( $this->mReturnTo !== '' ) {
1631 $query['returnto'] = $this->mReturnTo;
1632 $query['returntoquery'] = $this->mReturnToQuery;
1634 $check = $titleObj->getFullURL( $query );
1636 $this->getOutput()->redirect( $check );
1640 * @param string $type
1641 * @private
1643 function onCookieRedirectCheck( $type ) {
1644 if ( !$this->hasSessionCookie() ) {
1645 if ( $type == 'new' ) {
1646 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1647 } elseif ( $type == 'login' ) {
1648 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1649 } else {
1650 # shouldn't happen
1651 $this->mainLoginForm( $this->msg( 'error' )->text() );
1653 } else {
1654 $this->successfulLogin();
1659 * Produce a bar of links which allow the user to select another language
1660 * during login/registration but retain "returnto"
1662 * @return string
1664 function makeLanguageSelector() {
1665 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1666 if ( $msg->isBlank() ) {
1667 return '';
1669 $langs = explode( "\n", $msg->text() );
1670 $links = array();
1671 foreach ( $langs as $lang ) {
1672 $lang = trim( $lang, '* ' );
1673 $parts = explode( '|', $lang );
1674 if ( count( $parts ) >= 2 ) {
1675 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1679 return count( $links ) > 0 ? $this->msg( 'loginlanguagelabel' )->rawParams(
1680 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1684 * Create a language selector link for a particular language
1685 * Links back to this page preserving type and returnto
1687 * @param string $text Link text
1688 * @param string $lang Language code
1689 * @return string
1691 function makeLanguageSelectorLink( $text, $lang ) {
1692 if ( $this->getLanguage()->getCode() == $lang ) {
1693 // no link for currently used language
1694 return htmlspecialchars( $text );
1696 $query = array( 'uselang' => $lang );
1697 if ( $this->mType == 'signup' ) {
1698 $query['type'] = 'signup';
1700 if ( $this->mReturnTo !== '' ) {
1701 $query['returnto'] = $this->mReturnTo;
1702 $query['returntoquery'] = $this->mReturnToQuery;
1705 $attr = array();
1706 $targetLanguage = Language::factory( $lang );
1707 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1709 return Linker::linkKnown(
1710 $this->getPageTitle(),
1711 htmlspecialchars( $text ),
1712 $attr,
1713 $query
1717 protected function getGroupName() {
1718 return 'login';
1722 * Private function to check password expiration, until AuthManager comes
1723 * along to handle that.
1724 * @param User $user
1725 * @return string|bool
1727 private function checkUserPasswordExpired( User $user ) {
1728 global $wgPasswordExpireGrace;
1729 $dbr = wfGetDB( DB_SLAVE );
1730 $ts = $dbr->selectField( 'user', 'user_password_expires', array( 'user_id' => $user->getId() ) );
1732 $expired = false;
1733 $now = wfTimestamp();
1734 $expUnix = wfTimestamp( TS_UNIX, $ts );
1735 if ( $ts !== null && $expUnix < $now ) {
1736 $expired = ( $expUnix + $wgPasswordExpireGrace < $now ) ? 'hard' : 'soft';
1738 return $expired;