* @ingroup SpecialPage
*/
use MediaWiki\Logger\LoggerFactory;
+use Psr\Log\LogLevel;
use MediaWiki\Session\SessionManager;
/**
const WRONG_TOKEN = 13;
const USER_MIGRATED = 14;
- public static $statusCodes = array(
+ public static $statusCodes = [
self::SUCCESS => 'success',
self::NO_NAME => 'no_name',
self::ILLEGAL => 'illegal',
self::NEED_TOKEN => 'need_token',
self::WRONG_TOKEN => 'wrong_token',
self::USER_MIGRATED => 'user_migrated',
- );
+ ];
/**
* Valid error and warning messages
* @since 1.24
* @var string[]
*/
- public static $validErrorMessages = array(
+ public static $validErrorMessages = [
'exception-nologin-text',
'watchlistanontext',
'changeemail-no-info',
'resetpass-no-info',
'confirmemail_needlogin',
'prefsnologintext2',
- );
+ ];
public $mAbortLoginErrorMsg = null;
+ /**
+ * @var int How many seconds user is throttled for
+ * @since 1.27
+ */
+ public $mThrottleWait = '?';
protected $mUsername;
protected $mPassword;
static $messages = null;
if ( !$messages ) {
$messages = self::$validErrorMessages;
- Hooks::run( 'LoginFormValidErrorMessages', array( &$messages ) );
+ Hooks::run( 'LoginFormValidErrorMessages', [ &$messages ] );
}
return $messages;
$loginreqlink = Linker::linkKnown(
$this->getPageTitle(),
$this->msg( 'loginreqlink' )->escaped(),
- array(),
- array(
+ [],
+ [
'returnto' => $this->mReturnTo,
'returntoquery' => $this->mReturnToQuery,
'uselang' => $this->mLanguage,
'fromhttp' => $this->mFromHTTP ? '1' : '0',
- )
+ ]
);
// Only show valid error or warning messages.
throw new ErrorPageError(
'cannotloginnow-title',
'cannotloginnow-text',
- array(
+ [
$session->getProvider()->describe( RequestContext::getMain()->getLanguage() )
- )
+ ]
);
}
global $wgSecureLogin;
if ( $this->mRequest->getProtocol() !== 'https' ) {
$title = $this->getFullTitle();
- $query = array(
+ $query = [
'returnto' => $this->mReturnTo !== '' ? $this->mReturnTo : null,
'returntoquery' => $this->mReturnToQuery !== '' ?
$this->mReturnToQuery : null,
'title' => null,
( $this->mEntryErrorType === 'error' ? 'error' : 'warning' ) => $this->mEntryError,
- ) + $this->mRequest->getQueryValues();
+ ] + $this->mRequest->getQueryValues();
$url = $title->getFullURL( $query, false, PROTO_HTTPS );
if ( $wgSecureLogin
&& wfCanIPUseHTTPS( $this->getRequest()->getIP() )
$status = $this->addNewAccountInternal();
LoggerFactory::getInstance( 'authmanager' )->info(
'Account creation attempt with mailed password',
- array( 'event' => 'accountcreation', 'status' => $status )
+ [ 'event' => 'accountcreation', 'status' => $status ]
);
if ( !$status->isGood() ) {
$error = $status->getMessage();
$u->saveSettings();
$result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
- Hooks::run( 'AddNewAccount', array( $u, true ) );
+ Hooks::run( 'AddNewAccount', [ $u, true ] );
$u->addNewUserLogEntry( 'byemail', $this->mReason );
$out = $this->getOutput();
# Create the account and abort if there's a problem doing so
$status = $this->addNewAccountInternal();
- LoggerFactory::getInstance( 'authmanager' )->info( 'Account creation attempt', array(
+ LoggerFactory::getInstance( 'authmanager' )->info( 'Account creation attempt', [
'event' => 'accountcreation',
'status' => $status,
- ) );
+ ] );
if ( !$status->isGood() ) {
$error = $status->getMessage();
// which is needed or the personal links will be
// wrong.
$this->getContext()->setUser( $u );
- Hooks::run( 'AddNewAccount', array( $u, false ) );
+ Hooks::run( 'AddNewAccount', [ $u, false ] );
$u->addNewUserLogEntry( 'create' );
if ( $this->hasSessionCookie() ) {
$this->successfulCreation();
$out->setPageTitle( $this->msg( 'accountcreated' ) );
$out->addWikiMsg( 'accountcreatedtext', $u->getName() );
$out->addReturnTo( $this->getPageTitle() );
- Hooks::run( 'AddNewAccount', array( $u, false ) );
+ Hooks::run( 'AddNewAccount', [ $u, false ] );
$u->addNewUserLogEntry( 'create2', $this->mReason );
}
$abortError = '';
$abortStatus = null;
- if ( !Hooks::run( 'AbortNewAccount', array( $u, &$abortError, &$abortStatus ) ) ) {
+ if ( !Hooks::run( 'AbortNewAccount', [ $u, &$abortError, &$abortStatus ] ) ) {
// Hook point to add extra creation throttles and blocks
wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
if ( $abortStatus === null ) {
// This will report the error back as 'createaccount-hook-aborted'
// with the given string as the message.
// To return a different error code, return a Status object.
- $abortError = new Message( 'createaccount-hook-aborted', array( $abortError ) );
+ $abortError = new Message( 'createaccount-hook-aborted', [ $abortError ] );
$abortError->text();
return Status::newFatal( $abortError );
}
// Hook point to check for exempt from account creation throttle
- if ( !Hooks::run( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
+ if ( !Hooks::run( 'ExemptFromAccountCreationThrottle', [ $ip ] ) ) {
wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook " .
"allowed account creation w/o throttle\n" );
} else {
if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
- $key = wfMemcKey( 'acctcreate', 'ip', $ip );
+ $key = wfGlobalCacheKey( 'acctcreate', 'ip', $ip );
$value = $cache->get( $key );
if ( !$value ) {
$cache->set( $key, 0, $cache::TTL_DAY );
$u->setRealName( $this->mRealName );
$u->setToken();
- Hooks::run( 'LocalUserCreated', array( $u, $autocreate ) );
+ Hooks::run( 'LocalUserCreated', [ $u, $autocreate ] );
$oldUser = $u;
$wgAuth->initUser( $u, $autocreate );
if ( $oldUser !== $u ) {
DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
// Watch user's userpage and talk page
- $u->addWatch( $u->getUserPage(), WatchedItem::IGNORE_USER_RIGHTS );
+ $u->addWatch( $u->getUserPage(), User::IGNORE_USER_RIGHTS );
return Status::newGood( $u );
}
return self::NEED_TOKEN;
}
- $throttleCount = self::incLoginThrottle( $this->mUsername );
- if ( $throttleCount === true ) {
+ $throttleCount = self::incrementLoginThrottle( $this->mUsername );
+ if ( $throttleCount ) {
+ $this->mThrottleWait = $throttleCount['wait'];
return self::THROTTLED;
}
$msg = null;
// Give extensions a way to indicate the username has been updated,
// rather than telling the user the account doesn't exist.
- if ( !Hooks::run( 'LoginUserMigrated', array( $u, &$msg ) ) ) {
+ if ( !Hooks::run( 'LoginUserMigrated', [ $u, &$msg ] ) ) {
$this->mAbortLoginErrorMsg = $msg;
return self::USER_MIGRATED;
}
// Give general extensions, such as a captcha, a chance to abort logins
$abort = self::ABORTED;
- if ( !Hooks::run( 'AbortLogin', array( $u, $this->mPassword, &$abort, &$msg ) ) ) {
+ if ( !Hooks::run( 'AbortLogin', [ $u, $this->mPassword, &$abort, &$msg ] ) ) {
if ( !in_array( $abort, array_keys( self::$statusCodes ), true ) ) {
throw new Exception( 'Invalid status code returned from AbortLogin hook: ' . $abort );
}
$retval = self::RESET_PASS;
$this->mAbortLoginErrorMsg = 'resetpass-expired';
} else {
- Hooks::run( 'UserLoggedIn', array( $u ) );
+ Hooks::run( 'UserLoggedIn', [ $u ] );
$oldUser = $u;
$wgAuth->updateUser( $u );
if ( $oldUser !== $u ) {
$this->getContext()->setUser( $u );
// Please reset throttle for successful logins, thanks!
- if ( $throttleCount ) {
- self::clearLoginThrottle( $this->mUsername );
- }
+ self::clearLoginThrottle( $this->mUsername );
if ( $isAutoCreated ) {
// Must be run after $wgUser is set, for correct new user log
- Hooks::run( 'AuthPluginAutoCreate', array( $u ) );
+ Hooks::run( 'AuthPluginAutoCreate', [ $u ] );
}
$retval = self::SUCCESS;
}
- Hooks::run( 'LoginAuthenticateAudit', array( $u, $this->mPassword, $retval ) );
+ Hooks::run( 'LoginAuthenticateAudit', [ $u, $this->mPassword, $retval ] );
return $retval;
}
/**
* Increment the login attempt throttle hit count for the (username,current IP)
* tuple unless the throttle was already reached.
+ *
+ * @since 1.27 Return value changed.
* @param string $username The user name
- * @return bool|int The integer hit count or True if it is already at the limit
+ * @return bool|array false if below limit or an array if above limit
+ * Array contains keys wait, count, and throttleIndex
*/
- public static function incLoginThrottle( $username ) {
+ public static function incrementLoginThrottle( $username ) {
global $wgPasswordAttemptThrottle, $wgRequest;
- $username = trim( $username ); // sanity
+ $username = User::getCanonicalName( $username, 'usable' ) ?: $username;
$throttleCount = 0;
if ( is_array( $wgPasswordAttemptThrottle ) ) {
- $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
- $count = $wgPasswordAttemptThrottle['count'];
- $period = $wgPasswordAttemptThrottle['seconds'];
-
- $cache = ObjectCache::getLocalClusterInstance();
- $throttleCount = $cache->get( $throttleKey );
- if ( !$throttleCount ) {
- $cache->add( $throttleKey, 1, $period ); // start counter
- } elseif ( $throttleCount < $count ) {
- $cache->incr( $throttleKey );
- } elseif ( $throttleCount >= $count ) {
- return true;
+ $throttleConfig = $wgPasswordAttemptThrottle;
+ if ( isset( $wgPasswordAttemptThrottle['count'] ) ) {
+ // old style. Convert for backwards compat.
+ $throttleConfig = [ $wgPasswordAttemptThrottle ];
+ }
+ foreach ( $throttleConfig as $index => $specificThrottle ) {
+ if ( isset( $specificThrottle['allIPs'] ) ) {
+ $ip = 'All';
+ } else {
+ $ip = $wgRequest->getIP();
+ }
+ $throttleKey = wfGlobalCacheKey( 'password-throttle',
+ $index, $ip, md5( $username )
+ );
+ $count = $specificThrottle['count'];
+ $period = $specificThrottle['seconds'];
+
+ $cache = ObjectCache::getLocalClusterInstance();
+ $throttleCount = $cache->get( $throttleKey );
+ if ( !$throttleCount ) {
+ $cache->add( $throttleKey, 1, $period ); // start counter
+ } elseif ( $throttleCount < $count ) {
+ $cache->incr( $throttleKey );
+ } elseif ( $throttleCount >= $count ) {
+ $logMsg = 'Login attempt rejected because logins to '
+ . '{acct} from IP {ip} have been throttled for '
+ . '{period} seconds due to {count} failed attempts';
+ // If we are hitting a throttle for >= 50 attempts,
+ // it is much more likely to be an attack than someone
+ // simply forgetting their password, so log it at a
+ // higher level.
+ $level = $count >= 50 ? LogLevel::WARNING : LogLevel::INFO;
+ // It should be noted that once the throttle is hit,
+ // every attempt to login will generate the log message
+ // until the throttle expires, not just the attempt that
+ // puts the throttle over the top.
+ LoggerFactory::getInstance( 'password-throttle' )->log(
+ $level,
+ $logMsg,
+ [
+ 'ip' => $ip,
+ 'period' => $period,
+ 'acct' => $username,
+ 'count' => $count,
+ 'throttleIdentifier' => $index,
+ 'method' => __METHOD__
+ ]
+ );
+
+ return [
+ 'throttleIndex' => $index,
+ 'wait' => $period,
+ 'count' => $count
+ ];
+ }
}
}
+ return false;
+ }
- return $throttleCount;
+ /**
+ * Increment the login attempt throttle hit count for the (username,current IP)
+ * tuple unless the throttle was already reached.
+ *
+ * @deprecated Use LoginForm::incrementLoginThrottle instead
+ * @param string $username The user name
+ * @return bool|int true if above throttle, or 0 (prior to 1.27, returned current count)
+ */
+ public static function incLoginThrottle( $username ) {
+ wfDeprecated( __METHOD__, "1.27" );
+ $res = self::incrementLoginThrottle( $username );
+ return is_array( $res ) ? true : 0;
}
/**
* @return void
*/
public static function clearLoginThrottle( $username ) {
- global $wgRequest;
- $username = trim( $username ); // sanity
+ global $wgRequest, $wgPasswordAttemptThrottle;
+ $username = User::getCanonicalName( $username, 'usable' ) ?: $username;
- $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
- ObjectCache::getLocalClusterInstance()->delete( $throttleKey );
+ if ( is_array( $wgPasswordAttemptThrottle ) ) {
+ $throttleConfig = $wgPasswordAttemptThrottle;
+ if ( isset( $wgPasswordAttemptThrottle['count'] ) ) {
+ // old style. Convert for backwards compat.
+ $throttleConfig = [ $wgPasswordAttemptThrottle ];
+ }
+ foreach ( $throttleConfig as $index => $specificThrottle ) {
+ if ( isset( $specificThrottle['allIPs'] ) ) {
+ $ip = 'All';
+ } else {
+ $ip = $wgRequest->getIP();
+ }
+ $throttleKey = wfGlobalCacheKey( 'password-throttle', $index,
+ $ip, md5( $username )
+ );
+ ObjectCache::getLocalClusterInstance()->delete( $throttleKey );
+ }
+ }
}
/**
}
$abortError = '';
- if ( !Hooks::run( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
+ if ( !Hooks::run( 'AbortAutoAccount', [ $user, &$abortError ] ) ) {
// Hook point to add extra creation throttles and blocks
wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
$this->mAbortLoginErrorMsg = $abortError;
}
function processLogin() {
- global $wgLang, $wgSecureLogin, $wgPasswordAttemptThrottle, $wgInvalidPasswordReset;
+ global $wgLang, $wgSecureLogin, $wgInvalidPasswordReset;
$cache = ObjectCache::getLocalClusterInstance();
$authRes = $this->authenticateUserData();
self::clearLoginToken();
// Reset the throttle
- $request = $this->getRequest();
- $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername ) );
- $cache->delete( $key );
+ self::clearLoginThrottle( $this->mUsername );
+ $request = $this->getRequest();
if ( $this->hasSessionCookie() || $this->mSkipCookieCheck ) {
/* Replace the language object to provide user interface in
* correct language immediately on this first page load.
$code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
$userLang = Language::factory( $code );
$wgLang = $userLang;
+ RequestContext::getMain()->setLanguage( $userLang );
$this->getContext()->setLanguage( $userLang );
// Reset SessionID on Successful login (bug 40995)
$this->renewSessionId();
case self::THROTTLED:
$error = $this->mAbortLoginErrorMsg ?: 'login-throttled';
$this->mainLoginForm( $this->msg( $error )
- ->params( $this->getLanguage()->formatDuration( $wgPasswordAttemptThrottle['seconds'] ) )
- ->text()
+ ->durationParams( $this->mThrottleWait )->text()
);
break;
case self::USER_BLOCKED:
break;
case self::USER_MIGRATED:
$error = $this->mAbortLoginErrorMsg ?: 'login-migrated-generic';
- $params = array();
+ $params = [];
if ( is_array( $error ) ) {
$error = array_shift( $this->mAbortLoginErrorMsg );
$params = $this->mAbortLoginErrorMsg;
throw new MWException( 'Unhandled case value' );
}
- LoggerFactory::getInstance( 'authmanager' )->info( 'Login attempt', array(
+ LoggerFactory::getInstance( 'authmanager' )->info( 'Login attempt', [
'event' => 'login',
'successful' => $authRes === self::SUCCESS,
'status' => LoginForm::$statusCodes[$authRes],
- ) );
+ ] );
}
/**
*/
protected function resetLoginForm( Message $msg ) {
// Allow hooks to explain this password reset in more detail
- Hooks::run( 'LoginPasswordResetMessage', array( &$msg, $this->mUsername ) );
+ Hooks::run( 'LoginPasswordResetMessage', [ &$msg, $this->mUsername ] );
$reset = new SpecialChangePassword();
$derivative = new DerivativeContext( $this->getContext() );
$derivative->setTitle( $reset->getPageTitle() );
}
$currentUser = $this->getUser();
- Hooks::run( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
+ Hooks::run( 'User::mailPasswordInternal', [ &$currentUser, &$ip, &$u ] );
$np = PasswordFactory::generateRandomPasswordString( $wgMinimalPasswordLength );
$u->setNewpassword( $np, $throttle );
# Run any hooks; display injected HTML if any, else redirect
$currentUser = $this->getUser();
$injected_html = '';
- Hooks::run( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
+ Hooks::run( 'UserLoginComplete', [ &$currentUser, &$injected_html ] );
if ( $injected_html !== '' ) {
$this->displaySuccessfulAction( 'success', $this->msg( 'loginsuccesstitle' ),
$injected_html = '';
$welcome_creation_msg = 'welcomecreation-msg';
- Hooks::run( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
+ Hooks::run( 'UserLoginComplete', [ &$currentUser, &$injected_html ] );
/**
* Let any extensions change what message is shown.
* @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
* @since 1.18
*/
- Hooks::run( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
+ Hooks::run( 'BeforeWelcomeCreation', [ &$welcome_creation_msg, &$injected_html ] );
$this->displaySuccessfulAction(
'signup',
# haven't bothered to log out before trying to create an account to
# evade it, but we'll leave that to their guilty conscience to figure
# out.
- $errorParams = array(
+ $errorParams = [
$block->getTarget(),
$block->mReason ? $block->mReason : $this->msg( 'blockednoreason' )->text(),
$block->getByName()
- );
+ ];
if ( $block->getType() === Block::TYPE_RANGE ) {
$errorMessage = 'cantcreateaccount-range-text';
if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
$returnTo = $wgRedirectOnLogin;
- $returnToQuery = array();
+ $returnToQuery = [];
} else {
$returnTo = $this->mReturnTo;
$returnToQuery = wfCgiToArray( $this->mReturnToQuery );
}
// Allow modification of redirect behavior
- Hooks::run( 'PostLoginRedirect', array( &$returnTo, &$returnToQuery, &$type ) );
+ Hooks::run( 'PostLoginRedirect', [ &$returnTo, &$returnToQuery, &$type ] );
$returnToTitle = Title::newFromText( $returnTo );
if ( !$returnToTitle ) {
}
if ( $wgSecureLogin && !$this->mStickHTTPS ) {
- $options = array( 'http' );
+ $options = [ 'http' ];
$proto = PROTO_HTTP;
} elseif ( $wgSecureLogin ) {
- $options = array( 'https' );
+ $options = [ 'https' ];
$proto = PROTO_HTTPS;
} else {
- $options = array();
+ $options = [];
$proto = PROTO_RELATIVE;
}
}
// Generic styles and scripts for both login and signup form
- $out->addModuleStyles( array(
+ $out->addModuleStyles( [
'mediawiki.ui',
'mediawiki.ui.button',
'mediawiki.ui.checkbox',
'mediawiki.ui.input',
'mediawiki.special.userlogin.common.styles'
- ) );
+ ] );
if ( $this->mType == 'signup' ) {
// Additional styles and scripts for signup form
- $out->addModules( array(
+ $out->addModules( [
'mediawiki.special.userlogin.signup.js'
- ) );
- $out->addModuleStyles( array(
+ ] );
+ $out->addModuleStyles( [
'mediawiki.special.userlogin.signup.styles'
- ) );
+ ] );
$template = new UsercreateTemplate( $this->getConfig() );
$linkq = 'type=login';
} else {
// Additional styles for login form
- $out->addModuleStyles( array(
+ $out->addModuleStyles( [
'mediawiki.special.userlogin.login.styles'
- ) );
+ ] );
$template = new UserloginTemplate( $this->getConfig() );
// Give authentication and captcha plugins a chance to modify the form
$wgAuth->modifyUITemplate( $template, $this->mType );
if ( $this->mType == 'signup' ) {
- Hooks::run( 'UserCreateForm', array( &$template ) );
+ Hooks::run( 'UserCreateForm', [ &$template ] );
} else {
- Hooks::run( 'UserLoginForm', array( &$template ) );
+ Hooks::run( 'UserLoginForm', [ &$template ] );
}
$out->disallowUserJs(); // just in case...
*/
function cookieRedirectCheck( $type ) {
$titleObj = SpecialPage::getTitleFor( 'Userlogin' );
- $query = array( 'wpCookieCheck' => $type );
+ $query = [ 'wpCookieCheck' => $type ];
if ( $this->mReturnTo !== '' ) {
$query['returnto'] = $this->mReturnTo;
$query['returntoquery'] = $this->mReturnToQuery;
return '';
}
$langs = explode( "\n", $msg->text() );
- $links = array();
+ $links = [];
foreach ( $langs as $lang ) {
$lang = trim( $lang, '* ' );
$parts = explode( '|', $lang );
// no link for currently used language
return htmlspecialchars( $text );
}
- $query = array( 'uselang' => $lang );
+ $query = [ 'uselang' => $lang ];
if ( $this->mType == 'signup' ) {
$query['type'] = 'signup';
}
$query['returntoquery'] = $this->mReturnToQuery;
}
- $attr = array();
+ $attr = [];
$targetLanguage = Language::factory( $lang );
$attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
private function checkUserPasswordExpired( User $user ) {
global $wgPasswordExpireGrace;
$dbr = wfGetDB( DB_SLAVE );
- $ts = $dbr->selectField( 'user', 'user_password_expires', array( 'user_id' => $user->getId() ) );
+ $ts = $dbr->selectField( 'user', 'user_password_expires', [ 'user_id' => $user->getId() ] );
$expired = false;
$now = wfTimestamp();
return $expired;
}
+ protected function getSubpagesForPrefixSearch() {
+ return [ 'signup' ];
+ }
}