Cleanup r61694, move blocked check to after password check, global auth checks, etc...
[lhc/web/wiklou.git] / includes / specials / SpecialUserlogin.php
index 551d9c0..671070b 100644 (file)
@@ -34,18 +34,21 @@ class LoginForm {
        const ABORTED = 8;
        const CREATE_BLOCKED = 9;
        const THROTTLED = 10;
+       const USER_BLOCKED = 11;
 
        var $mName, $mPassword, $mRetype, $mReturnTo, $mCookieCheck, $mPosted;
        var $mAction, $mCreateaccount, $mCreateaccountMail, $mMailmypassword;
-       var $mLoginattempt, $mRemember, $mEmail, $mDomain, $mLanguage, $mSkipCookieCheck;
+       var $mLoginattempt, $mRemember, $mEmail, $mDomain, $mLanguage;
+       var $mSkipCookieCheck, $mReturnToQuery;
+
+       private $mExtUser = null;
 
        /**
         * Constructor
         * @param WebRequest $request A WebRequest object passed by reference
         */
        function LoginForm( &$request, $par = '' ) {
-               global $wgLang, $wgAllowRealName, $wgEnableEmail;
-               global $wgAuth;
+               global $wgAuth, $wgHiddenPrefs, $wgEnableEmail, $wgRedirectOnLogin;
 
                $this->mType = ( $par == 'signup' ) ? $par : $request->getText( 'type' ); # Check for [[Special:Userlogin/signup]]
                $this->mName = $request->getText( 'wpName' );
@@ -53,6 +56,7 @@ class LoginForm {
                $this->mRetype = $request->getText( 'wpRetype' );
                $this->mDomain = $request->getText( 'wpDomain' );
                $this->mReturnTo = $request->getVal( 'returnto' );
+               $this->mReturnToQuery = $request->getVal( 'returntoquery' );
                $this->mCookieCheck = $request->getVal( 'wpCookieCheck' );
                $this->mPosted = $request->wasPosted();
                $this->mCreateaccount = $request->getCheck( 'wpCreateaccount' );
@@ -66,12 +70,17 @@ class LoginForm {
                $this->mLanguage = $request->getText( 'uselang' );
                $this->mSkipCookieCheck = $request->getCheck( 'wpSkipCookieCheck' );
 
+               if ( $wgRedirectOnLogin ) {
+                       $this->mReturnTo = $wgRedirectOnLogin;
+                       $this->mReturnToQuery = '';
+               }
+
                if( $wgEnableEmail ) {
                        $this->mEmail = $request->getText( 'wpEmail' );
                } else {
                        $this->mEmail = '';
                }
-               if( $wgAllowRealName ) {
+               if( !in_array( 'realname', $wgHiddenPrefs ) ) {
                    $this->mRealName = $request->getText( 'wpRealName' );
                } else {
                    $this->mRealName = '';
@@ -83,8 +92,10 @@ class LoginForm {
                $wgAuth->setDomain( $this->mDomain );
 
                # When switching accounts, it sucks to get automatically logged out
-               if( $this->mReturnTo == $wgLang->specialPage( 'Userlogout' ) ) {
+               $returnToTitle = Title::newFromText( $this->mReturnTo );
+               if( is_object( $returnToTitle ) && $returnToTitle->isSpecial( 'Userlogout' ) ) {
                        $this->mReturnTo = '';
+                       $this->mReturnToQuery = '';
                }
        }
 
@@ -112,14 +123,14 @@ class LoginForm {
        function addNewAccountMailPassword() {
                global $wgOut;
 
-               if ('' == $this->mEmail) {
+               if ( $this->mEmail == '' ) {
                        $this->mainLoginForm( wfMsg( 'noemail', htmlspecialchars( $this->mName ) ) );
                        return;
                }
 
                $u = $this->addNewaccountInternal();
 
-               if ($u == NULL) {
+               if ($u == null) {
                        return;
                }
 
@@ -129,6 +140,7 @@ class LoginForm {
                $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
 
                wfRunHooks( 'AddNewAccount', array( $u, true ) );
+               $u->addNewUserLogEntry();
 
                $wgOut->setPageTitle( wfMsg( 'accmailtitle' ) );
                $wgOut->setRobotPolicy( 'noindex,nofollow' );
@@ -152,7 +164,7 @@ class LoginForm {
 
                # Create the account and abort if there's a problem doing so
                $u = $this->addNewAccountInternal();
-               if( $u == NULL )
+               if( $u == null )
                        return;
 
                # If we showed up language selection links, and one was in use, be
@@ -175,14 +187,16 @@ class LoginForm {
                # Save settings (including confirmation token)
                $u->saveSettings();
 
-               # If not logged in, assume the new account as the current one and set session cookies
-               # then show a "welcome" message or a "need cookies" message as needed
+               # If not logged in, assume the new account as the current one and set
+               # session cookies then show a "welcome" message or a "need cookies"
+               # message as needed
                if( $wgUser->isAnon() ) {
                        $wgUser = $u;
                        $wgUser->setCookies();
-                       wfRunHooks( 'AddNewAccount', array( $wgUser ) );
+                       wfRunHooks( 'AddNewAccount', array( $wgUser, false ) );
+                       $wgUser->addNewUserLogEntry();
                        if( $this->hasSessionCookie() ) {
-                               return $this->successfulLogin( 'welcomecreation', $wgUser->getName(), false );
+                               return $this->successfulCreation();
                        } else {
                                return $this->cookieRedirectCheck( 'new' );
                        }
@@ -193,9 +207,10 @@ class LoginForm {
                        $wgOut->setPageTitle( wfMsgHtml( 'accountcreated' ) );
                        $wgOut->setArticleRelated( false );
                        $wgOut->setRobotPolicy( 'noindex,nofollow' );
-                       $wgOut->addHtml( wfMsgWikiHtml( 'accountcreatedtext', $u->getName() ) );
+                       $wgOut->addHTML( wfMsgWikiHtml( 'accountcreatedtext', $u->getName() ) );
                        $wgOut->returnToMain( false, $self );
-                       wfRunHooks( 'AddNewAccount', array( $u ) );
+                       wfRunHooks( 'AddNewAccount', array( $u, false ) );
+                       $u->addNewUserLogEntry();
                        return true;
                }
        }
@@ -205,7 +220,6 @@ class LoginForm {
         */
        function addNewAccountInternal() {
                global $wgUser, $wgOut;
-               global $wgEnableSorbs, $wgProxyWhitelist;
                global $wgMemc, $wgAccountCreationThrottle;
                global $wgAuth, $wgMinimalPasswordLength;
                global $wgEmailConfirmToEdit;
@@ -216,13 +230,12 @@ class LoginForm {
                        return false;
                }
 
-               // If we are not allowing users to login locally, we should
-               // be checking to see if the user is actually able to
-               // authenticate to the authentication server before they
-               // create an account (otherwise, they can create a local account
-               // and login as any domain user). We only need to check this for
-               // domains that aren't local.
-               if( 'local' != $this->mDomain && '' != $this->mDomain ) {
+               // If we are not allowing users to login locally, we should be checking
+               // to see if the user is actually able to authenticate to the authenti-
+               // cation server before they create an account (otherwise, they can
+               // create a local account and login as any domain user). We only need
+               // to check this for domains that aren't local.
+               if( 'local' != $this->mDomain && $this->mDomain != '' ) {
                        if( !$wgAuth->canCreateAccounts() && ( !$wgAuth->userExists( $this->mName ) || !$wgAuth->authenticate( $this->mName, $this->mPassword ) ) ) {
                                $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
                                return false;
@@ -244,9 +257,7 @@ class LoginForm {
                }
 
                $ip = wfGetIP();
-               if ( $wgEnableSorbs && !in_array( $ip, $wgProxyWhitelist ) &&
-                 $wgUser->inSorbsBlacklist( $ip ) )
-               {
+               if ( $wgUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
                        $this->mainLoginForm( wfMsg( 'sorbs_create_account_reason' ) . ' (' . htmlspecialchars( $ip ) . ')' );
                        return;
                }
@@ -254,7 +265,12 @@ class LoginForm {
                # Now create a dummy user ($u) and check if it is valid
                $name = trim( $this->mName );
                $u = User::newFromName( $name, 'creatable' );
-               if ( is_null( $u ) ) {
+               if ( WikiError::isError( $u ) ) {
+                       $this->mainLoginForm( wfMsg( $u->getMessage() ) );
+                       return false;
+               }
+
+               if ( !is_object( $u ) ) {
                        $this->mainLoginForm( wfMsg( 'noname' ) );
                        return false;
                }
@@ -270,9 +286,10 @@ class LoginForm {
                }
 
                # check for minimal password length
-               if ( !$u->isValidPassword( $this->mPassword ) ) {
+               $valid = $u->getPasswordValidity( $this->mPassword );
+               if ( $valid !== true ) {
                        if ( !$this->mCreateaccountMail ) {
-                               $this->mainLoginForm( wfMsgExt( 'passwordtooshort', array( 'parsemag' ), $wgMinimalPasswordLength ) );
+                               $this->mainLoginForm( wfMsgExt( $valid, array( 'parsemag' ), $wgMinimalPasswordLength ) );
                                return false;
                        } else {
                                # do not force a password for account creation by email
@@ -281,7 +298,8 @@ class LoginForm {
                        }
                }
 
-               # if you need a confirmed email address to edit, then obviously you need an email address.
+               # if you need a confirmed email address to edit, then obviously you
+               # need an email address.
                if ( $wgEmailConfirmToEdit && empty( $this->mEmail ) ) {
                        $this->mainLoginForm( wfMsg( 'noemailtitle' ) );
                        return false;
@@ -292,8 +310,8 @@ class LoginForm {
                        return false;
                }
 
-               # Set some additional data so the AbortNewAccount hook can be
-               # used for more than just username validation
+               # Set some additional data so the AbortNewAccount hook can be used for
+               # more than just username validation
                $u->setEmail( $this->mEmail );
                $u->setRealName( $this->mRealName );
 
@@ -307,14 +325,15 @@ class LoginForm {
 
                if ( $wgAccountCreationThrottle && $wgUser->isPingLimitable() ) {
                        $key = wfMemcKey( 'acctcreate', 'ip', $ip );
-                       $value = $wgMemc->incr( $key );
+                       $value = $wgMemc->get( $key );
                        if ( !$value ) {
-                               $wgMemc->set( $key, 1, 86400 );
+                               $wgMemc->set( $key, 0, 86400 );
                        }
-                       if ( $value > $wgAccountCreationThrottle ) {
+                       if ( $value >= $wgAccountCreationThrottle ) {
                                $this->throttleHit( $wgAccountCreationThrottle );
                                return false;
                        }
+                       $wgMemc->incr( $key );
                }
 
                if( !$wgAuth->addUser( $u, $this->mPassword, $this->mEmail, $this->mRealName ) ) {
@@ -349,6 +368,14 @@ class LoginForm {
 
                $wgAuth->initUser( $u, $autocreate );
 
+               if ( $this->mExtUser ) {
+                       $this->mExtUser->linkToLocal( $u->getId() );
+                       $email = $this->mExtUser->getPref( 'emailaddress' );
+                       if ( $email && !$this->mEmail ) {
+                               $u->setEmail( $email );
+                       }
+               }
+
                $u->setOption( 'rememberpassword', $this->mRemember ? 1 : 0 );
                $u->saveSettings();
 
@@ -365,41 +392,47 @@ class LoginForm {
         * This may create a local account as a side effect if the
         * authentication plugin allows transparent local account
         * creation.
-        *
-        * @public
         */
-       function authenticateUserData() {
+       public function authenticateUserData() {
                global $wgUser, $wgAuth;
-               if ( '' == $this->mName ) {
+               if ( $this->mName == '' ) {
                        return self::NO_NAME;
                }
                
                global $wgPasswordAttemptThrottle;
-               if ( is_array($wgPasswordAttemptThrottle) ) {
-                       $key = wfMemcKey( 'password-throttle', wfGetIP(), md5( $this->mName ) );
+
+               $throttleCount = 0;
+               if ( is_array( $wgPasswordAttemptThrottle ) ) {
+                       $throttleKey = wfMemcKey( 'password-throttle', wfGetIP(), md5( $this->mName ) );
                        $count = $wgPasswordAttemptThrottle['count'];
                        $period = $wgPasswordAttemptThrottle['seconds'];
                        
                        global $wgMemc;
-                       $cur = $wgMemc->get($key);
-                       if ( !$cur ) {
-                               $wgMemc->add( $key, 1, $period ); // start counter
-                       } else if ( $cur < $count ) {
-                               $wgMemc->incr($key);
-                       } else if ( $cur >= $count ) {
+                       $throttleCount = $wgMemc->get( $throttleKey );
+                       if ( !$throttleCount ) {
+                               $wgMemc->add( $throttleKey, 1, $period ); // start counter
+                       } else if ( $throttleCount < $count ) {
+                               $wgMemc->incr($throttleKey);
+                       } else if ( $throttleCount >= $count ) {
                                return self::THROTTLED;
                        }
                }
 
-               // Load $wgUser now, and check to see if we're logging in as the same name. 
-               // This is necessary because loading $wgUser (say by calling getName()) calls
-               // the UserLoadFromSession hook, which potentially creates the user in the 
-               // database. Until we load $wgUser, checking for user existence using 
-               // User::newFromName($name)->getId() below will effectively be using stale data.
+               // Load $wgUser now, and check to see if we're logging in as the same
+               // name. This is necessary because loading $wgUser (say by calling
+               // getName()) calls the UserLoadFromSession hook, which potentially
+               // creates the user in the database. Until we load $wgUser, checking
+               // for user existence using User::newFromName($name)->getId() below
+               // will effectively be using stale data.
                if ( $wgUser->getName() === $this->mName ) {
                        wfDebug( __METHOD__.": already logged in as {$this->mName}\n" );
                        return self::SUCCESS;
                }
+
+               $this->mExtUser = ExternalUser::newFromName( $this->mName );
+
+               # TODO: Allow some magic here for invalid external names, e.g., let the
+               # user choose a different wiki name.
                $u = User::newFromName( $this->mName );
                if( is_null( $u ) || !User::isUsableName( $u->getName() ) ) {
                        return self::ILLEGAL;
@@ -414,6 +447,15 @@ class LoginForm {
                                $isAutoCreated = true;
                        }
                } else {
+                       global $wgExternalAuthType, $wgAutocreatePolicy;
+                       if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
+                       && is_object( $this->mExtUser )
+                       && $this->mExtUser->authenticate( $this->mPassword ) ) {
+                               # The external user and local user have the same name and
+                               # password, so we assume they're the same.
+                               $this->mExtUser->linkToLocal( $u->getID() );
+                       }
+
                        $u->load();
                }
 
@@ -423,44 +465,49 @@ class LoginForm {
                        return $abort;
                }
 
+               global $wgBlockDisablesLogin;
                if (!$u->checkPassword( $this->mPassword )) {
                        if( $u->checkTemporaryPassword( $this->mPassword ) ) {
-                               // The e-mailed temporary password should not be used
-                               // for actual logins; that's a very sloppy habit,
-                               // and insecure if an attacker has a few seconds to
-                               // click "search" on someone's open mail reader.
+                               // The e-mailed temporary password should not be used for actu-
+                               // al logins; that's a very sloppy habit, and insecure if an
+                               // attacker has a few seconds to click "search" on someone's o-
+                               // pen mail reader.
                                //
-                               // Allow it to be used only to reset the password
-                               // a single time to a new value, which won't be in
-                               // the user's e-mail archives.
+                               // Allow it to be used only to reset the password a single time
+                               // to a new value, which won't be in the user's e-mail ar-
+                               // chives.
                                //
-                               // For backwards compatibility, we'll still recognize
-                               // it at the login form to minimize surprises for
-                               // people who have been logging in with a temporary
-                               // password for some time.
-                               //
-                               // As a side-effect, we can authenticate the user's
-                               // e-mail address if it's not already done, since
-                               // the temporary password was sent via e-mail.
+                               // For backwards compatibility, we'll still recognize it at the
+                               // login form to minimize surprises for people who have been
+                               // logging in with a temporary password for some time.
                                //
+                               // As a side-effect, we can authenticate the user's e-mail ad-
+                               // dress if it's not already done, since the temporary password
+                               // was sent via e-mail.
                                if( !$u->isEmailConfirmed() ) {
                                        $u->confirmEmail();
                                        $u->saveSettings();
                                }
 
-                               // At this point we just return an appropriate code
-                               // indicating that the UI should show a password
-                               // reset form; bot interfaces etc will probably just
-                               // fail cleanly here.
-                               //
+                               // At this point we just return an appropriate code/ indicating
+                               // that the UI should show a password reset form; bot inter-
+                               // faces etc will probably just fail cleanly here.
                                $retval = self::RESET_PASS;
                        } else {
-                               $retval = '' == $this->mPassword ? self::EMPTY_PASS : self::WRONG_PASS;
+                               $retval = ($this->mPassword  == '') ? self::EMPTY_PASS : self::WRONG_PASS;
                        }
+               } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
+                       // If we've enabled it, make it so that a blocked user cannot login
+                       $retval = self::USER_BLOCKED;
                } else {
                        $wgAuth->updateUser( $u );
                        $wgUser = $u;
 
+                       // Please reset throttle for successful logins, thanks!
+                       if($throttleCount) {
+                               $wgMemc->delete($throttleKey);
+                       }
+
                        if ( $isAutoCreated ) {
                                // Must be run after $wgUser is set, for correct new user log
                                wfRunHooks( 'AuthPluginAutoCreate', array( $wgUser ) );
@@ -473,39 +520,45 @@ class LoginForm {
        }
 
        /**
-        * Attempt to automatically create a user on login.
-        * Only succeeds if there is an external authentication method which allows it.
+        * Attempt to automatically create a user on login. Only succeeds if there
+        * is an external authentication method which allows it.
         * @return integer Status code
         */
        function attemptAutoCreate( $user ) {
-               global $wgAuth, $wgUser;
-               /**
-                * If the external authentication plugin allows it,
-                * automatically create a new account for users that
-                * are externally defined but have not yet logged in.
-                */
-               if ( !$wgAuth->autoCreate() ) {
-                       return self::NOT_EXISTS;
-               }
-               if ( !$wgAuth->userExists( $user->getName() ) ) {
-                       wfDebug( __METHOD__.": user does not exist\n" );
-                       return self::NOT_EXISTS;
-               }
-               if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword ) ) {
-                       wfDebug( __METHOD__.": \$wgAuth->authenticate() returned false, aborting\n" );
-                       return self::WRONG_PLUGIN_PASS;
-               }
+               global $wgAuth, $wgUser, $wgAutocreatePolicy;
+
                if ( $wgUser->isBlockedFromCreateAccount() ) {
                        wfDebug( __METHOD__.": user is blocked from account creation\n" );
                        return self::CREATE_BLOCKED;
                }
 
-               $abortError = '';
-               if( !wfRunHooks( 'AbortNewAccount', array( $user->getName(), &$abortError ) ) ) {
-                       // Hook point to add extra creation throttles and blocks
-                       wfDebug(  __METHOD__.": a hook blocked creation\n" );
-                       $this->mainLoginForm( $abortError );
-                       return self::ABORTED;
+               /**
+                * If the external authentication plugin allows it, automatically cre-
+                * ate a new account for users that are externally defined but have not
+                * yet logged in.
+                */
+               if ( $this->mExtUser ) {
+                       # mExtUser is neither null nor false, so use the new ExternalAuth
+                       # system.
+                       if ( $wgAutocreatePolicy == 'never' ) {
+                               return self::NOT_EXISTS;
+                       }
+                       if ( !$this->mExtUser->authenticate( $this->mPassword ) ) {
+                               return self::WRONG_PLUGIN_PASS;
+                       }
+               } else {
+                       # Old AuthPlugin.
+                       if ( !$wgAuth->autoCreate() ) {
+                               return self::NOT_EXISTS;
+                       }
+                       if ( !$wgAuth->userExists( $user->getName() ) ) {
+                               wfDebug( __METHOD__.": user does not exist\n" );
+                               return self::NOT_EXISTS;
+                       }
+                       if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword ) ) {
+                               wfDebug( __METHOD__.": \$wgAuth->authenticate() returned false, aborting\n" );
+                               return self::WRONG_PLUGIN_PASS;
+                       }
                }
 
                wfDebug( __METHOD__.": creating account\n" );
@@ -516,8 +569,7 @@ class LoginForm {
        function processLogin() {
                global $wgUser, $wgAuth;
 
-               switch ($this->authenticateUserData())
-               {
+               switch ( $this->authenticateUserData() ) {
                        case self::SUCCESS:
                                # We've verified now, update the real record
                                if( (bool)$this->mRemember != (bool)$wgUser->getOption( 'rememberpassword' ) ) {
@@ -528,14 +580,19 @@ class LoginForm {
                                }
                                $wgUser->setCookies();
 
+                               // Reset the throttle
+                               $key = wfMemcKey( 'password-throttle', wfGetIP(), md5( $this->mName ) );
+                               global $wgMemc;
+                               $wgMemc->delete( $key );
+
                                if( $this->hasSessionCookie() || $this->mSkipCookieCheck ) {
-                                       /* Replace the language object to provide user interface in correct
-                                        * language immediately on this first page load.
+                                       /* Replace the language object to provide user interface in
+                                        * correct language immediately on this first page load.
                                         */
                                        global $wgLang, $wgRequest;
                                        $code = $wgRequest->getVal( 'uselang', $wgUser->getOption( 'language' ) );
                                        $wgLang = Language::factory( $code );
-                                       return $this->successfulLogin( 'loginsuccess', $wgUser->getName() );
+                                       return $this->successfulLogin();
                                } else {
                                        return $this->cookieRedirectCheck( 'login' );
                                }
@@ -550,7 +607,7 @@ class LoginForm {
                                break;
                        case self::NOT_EXISTS:
                                if( $wgUser->isAllowed( 'createaccount' ) ){
-                                       $this->mainLoginForm( wfMsg( 'nosuchuser', htmlspecialchars( $this->mName ) ) );
+                                       $this->mainLoginForm( wfMsgWikiHtml( 'nosuchuser', htmlspecialchars( $this->mName ) ) );
                                } else {
                                        $this->mainLoginForm( wfMsg( 'nosuchusershort', htmlspecialchars( $this->mName ) ) );
                                }
@@ -570,6 +627,9 @@ class LoginForm {
                        case self::THROTTLED:
                                $this->mainLoginForm( wfMsg( 'login-throttled' ) );
                                break;
+                       case self::USER_BLOCKED:
+                               $this->mainLoginForm( wfMsg( 'login-userblocked' ) );
+                               break;
                        default:
                                throw new MWException( "Unhandled case value" );
                }
@@ -577,8 +637,8 @@ class LoginForm {
 
        function resetLoginForm( $error ) {
                global $wgOut;
-               $wgOut->addWikiText( "<div class=\"errorbox\">$error</div>" );
-               $reset = new PasswordResetForm( $this->mName, $this->mPassword );
+               $wgOut->addHTML( Xml::element('p', array( 'class' => 'error' ), $error ) );
+               $reset = new SpecialResetpass();
                $reset->execute( null );
        }
 
@@ -587,7 +647,12 @@ class LoginForm {
         */
        function mailPassword() {
                global $wgUser, $wgOut, $wgAuth;
-
+               
+               if ( wfReadOnly() ) {
+                       $wgOut->readOnlyPage();
+                       return false;
+               }
+               
                if( !$wgAuth->allowPasswordChange() ) {
                        $this->mainLoginForm( wfMsg( 'resetpass_forbidden' ) );
                        return;
@@ -599,6 +664,13 @@ class LoginForm {
                        $this->mainLoginForm( wfMsg( 'blocked-mailpassword' ) );
                        return;
                }
+               
+               // Check for hooks
+               $error = null;
+               if ( ! wfRunHooks( 'UserLoginMailPassword', array( $this->mName, &$error ) ) ) {
+                       $this->mainLoginForm( $error );
+                       return;
+               }
 
                # Check against the rate limiter
                if( $wgUser->pingLimiter( 'mailpassword' ) ) {
@@ -606,7 +678,7 @@ class LoginForm {
                        return;
                }
 
-               if ( '' == $this->mName ) {
+               if ( $this->mName == '' ) {
                        $this->mainLoginForm( wfMsg( 'noname' ) );
                        return;
                }
@@ -616,14 +688,15 @@ class LoginForm {
                        return;
                }
                if ( 0 == $u->getID() ) {
-                       $this->mainLoginForm( wfMsg( 'nosuchuser', $u->getName() ) );
+                       $this->mainLoginForm( wfMsgWikiHtml( 'nosuchuser', htmlspecialchars( $u->getName() ) ) );
                        return;
                }
 
                # Check against password throttle
                if ( $u->isPasswordReminderThrottled() ) {
                        global $wgPasswordReminderResendTime;
-                       # Round the time in hours to 3 d.p., in case someone is specifying minutes or seconds.
+                       # Round the time in hours to 3 d.p., in case someone is specifying
+                       # minutes or seconds.
                        $this->mainLoginForm( wfMsgExt( 'throttled-mailpassword', array( 'parsemag' ),
                                round( $wgPasswordReminderResendTime, 3 ) ) );
                        return;
@@ -647,10 +720,9 @@ class LoginForm {
         * @private
         */
        function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
-               global $wgCookiePath, $wgCookieDomain, $wgCookiePrefix, $wgCookieSecure;
-               global $wgServer, $wgScript, $wgUser;
+               global $wgServer, $wgScript, $wgUser, $wgNewPasswordExpiry;
 
-               if ( '' == $u->getEmail() ) {
+               if ( $u->getEmail() == '' ) {
                        return new WikiError( wfMsg( 'noemail', $u->getName() ) );
                }
                $ip = wfGetIP();
@@ -663,38 +735,75 @@ class LoginForm {
                $np = $u->randomPassword();
                $u->setNewpassword( $np, $throttle );
                $u->saveSettings();
-
-               $m = wfMsg( $emailText, $ip, $u->getName(), $np, $wgServer . $wgScript );
-               $result = $u->sendMail( wfMsg( $emailTitle ), $m );
+               $userLanguage = $u->getOption( 'language' );
+               $m = wfMsgExt( $emailText, array( 'parsemag', 'language' => $userLanguage ), $ip, $u->getName(), $np,
+                               $wgServer . $wgScript, round( $wgNewPasswordExpiry / 86400 ) );
+               $result = $u->sendMail( wfMsgExt( $emailTitle, array( 'parsemag', 'language' => $userLanguage ) ), $m );
 
                return $result;
        }
 
 
        /**
-        * @param string $msg Message key that will be shown on success
-        * @param $params String: parameters for the above message
-        * @param bool $auto Toggle auto-redirect to main page; default true
+        * Run any hooks registered for logins, then HTTP redirect to
+        * $this->mReturnTo (or Main Page if that's undefined).  Formerly we had a
+        * nice message here, but that's really not as useful as just being sent to
+        * wherever you logged in from.  It should be clear that the action was
+        * successful, given the lack of error messages plus the appearance of your
+        * name in the upper right.
+        *
         * @private
         */
-       function successfulLogin( $msg, $params, $auto = true ) {
-               global $wgUser;
-               global $wgOut;
+       function successfulLogin() {
+               global $wgUser, $wgOut;
+
+               # Run any hooks; display injected HTML if any, else redirect
+               $injected_html = '';
+               wfRunHooks('UserLoginComplete', array(&$wgUser, &$injected_html));
 
-               # Run any hooks; ignore results
+               if( $injected_html !== '' ) {
+                       $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
+               } else {
+                       $titleObj = Title::newFromText( $this->mReturnTo );
+                       if ( !$titleObj instanceof Title ) {
+                               $titleObj = Title::newMainPage();
+                       }
+                       $wgOut->redirect( $titleObj->getFullURL( $this->mReturnToQuery ) );
+               }
+       }
 
+       /**
+        * Run any hooks registered for logins, then display a message welcoming
+        * the user.
+        *
+        * @private
+        */
+       function successfulCreation() {
+               global $wgUser, $wgOut;
+
+               # Run any hooks; display injected HTML
                $injected_html = '';
                wfRunHooks('UserLoginComplete', array(&$wgUser, &$injected_html));
 
+               $this->displaySuccessfulLogin( 'welcomecreation', $injected_html );
+       }
+
+       /**
+        * Display a "login successful" page.
+        */
+       private function displaySuccessfulLogin( $msgname, $injected_html ) {
+               global $wgOut, $wgUser;
+
                $wgOut->setPageTitle( wfMsg( 'loginsuccesstitle' ) );
                $wgOut->setRobotPolicy( 'noindex,nofollow' );
                $wgOut->setArticleRelated( false );
-               $wgOut->addWikiMsgArray( $msg, $params );
-               $wgOut->addHtml( $injected_html );
+               $wgOut->addWikiMsg( $msgname, $wgUser->getName() );
+               $wgOut->addHTML( $injected_html );
+
                if ( !empty( $this->mReturnTo ) ) {
-                       $wgOut->returnToMain( $auto, $this->mReturnTo );
+                       $wgOut->returnToMain( null, $this->mReturnTo, $this->mReturnToQuery );
                } else {
-                       $wgOut->returnToMain( $auto );
+                       $wgOut->returnToMain( null );
                }
        }
 
@@ -707,7 +816,8 @@ class LoginForm {
                $wgOut->setArticleRelated( false );
 
                $wgOut->addWikitext( $wgOut->formatPermissionsErrorMessage( $errors, 'createaccount' ) );
-               // Stuff that might want to be added at the end. For example, instructions if blocked.
+               // Stuff that might want to be added at the end. For example, instruc-
+               // tions if blocked.
                $wgOut->addWikiMsg( 'cantcreateaccount-nonblock-text' );
 
                $wgOut->returnToMain( false );
@@ -744,8 +854,8 @@ class LoginForm {
         * @private
         */
        function mainLoginForm( $msg, $msgtype = 'error' ) {
-               global $wgUser, $wgOut, $wgAllowRealName, $wgEnableEmail;
-               global $wgCookiePrefix, $wgAuth, $wgLoginLanguageSelector;
+               global $wgUser, $wgOut, $wgHiddenPrefs, $wgEnableEmail;
+               global $wgCookiePrefix, $wgLoginLanguageSelector;
                global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
                
                $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
@@ -766,7 +876,7 @@ class LoginForm {
                        }
                }
 
-               if ( '' == $this->mName ) {
+               if ( $this->mName == '' ) {
                        if ( $wgUser->isLoggedIn() ) {
                                $this->mName = $wgUser->getName();
                        } else {
@@ -790,6 +900,9 @@ class LoginForm {
 
                if ( !empty( $this->mReturnTo ) ) {
                        $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
+                       if ( !empty( $this->mReturnToQuery ) )
+                               $returnto .= '&returntoquery=' .
+                                       wfUrlencode( $this->mReturnToQuery );
                        $q .= $returnto;
                        $linkq .= $returnto;
                }
@@ -804,7 +917,7 @@ class LoginForm {
 
                # Don't show a "create account" link if the user can't
                if( $this->showCreateOrLoginLink( $wgUser ) )
-                       $template->set( 'link', wfMsgHtml( $linkmsg, $link ) );
+                       $template->set( 'link', wfMsgWikiHtml( $linkmsg, $link ) );
                else
                        $template->set( 'link', '' );
 
@@ -820,7 +933,7 @@ class LoginForm {
                $template->set( 'message', $msg );
                $template->set( 'messagetype', $msgtype );
                $template->set( 'createemail', $wgEnableEmail && $wgUser->isLoggedIn() );
-               $template->set( 'userealname', $wgAllowRealName );
+               $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
                $template->set( 'useemail', $wgEnableEmail );
                $template->set( 'emailrequired', $wgEmailConfirmToEdit );
                $template->set( 'canreset', $wgAuth->allowPasswordChange() );
@@ -835,14 +948,20 @@ class LoginForm {
                }
 
                // Give authentication and captcha plugins a chance to modify the form
-               $wgAuth->modifyUITemplate( $template );
+               $wgAuth->modifyUITemplate( $template, $this->mType );
                if ( $this->mType == 'signup' ) {
                        wfRunHooks( 'UserCreateForm', array( &$template ) );
                } else {
                        wfRunHooks( 'UserLoginForm', array( &$template ) );
                }
 
-               $wgOut->setPageTitle( wfMsg( 'userlogin' ) );
+               //Changes the title depending on permissions for creating account
+               if ( $wgUser->isAllowed( 'createaccount' ) ) {
+                       $wgOut->setPageTitle( wfMsg( 'userlogin' ) );
+               } else {
+                       $wgOut->setPageTitle( wfMsg( 'userloginnocreate' ) );
+               }
+
                $wgOut->setRobotPolicy( 'noindex,nofollow' );
                $wgOut->setArticleRelated( false );
                $wgOut->disallowUserJs();  // just in case...
@@ -865,9 +984,9 @@ class LoginForm {
        /**
         * Check if a session cookie is present.
         *
-        * This will not pick up a cookie set during _this_ request, but is
-        * meant to ensure that the client is returning the cookie which was
-        * set on a previous pass through the system.
+        * This will not pick up a cookie set during _this_ request, but is meant
+        * to ensure that the client is returning the cookie which was set on a
+        * previous pass through the system.
         *
         * @private
         */
@@ -883,7 +1002,9 @@ class LoginForm {
                global $wgOut;
 
                $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
-               $check = $titleObj->getFullURL( 'wpCookieCheck='.$type );
+               $query = array( 'wpCookieCheck' => $type );
+               if ( $this->mReturnTo ) $query['returnto'] = $this->mReturnTo;
+               $check = $titleObj->getFullURL( $query );
 
                return $wgOut->redirect( $check );
        }
@@ -892,8 +1013,6 @@ class LoginForm {
         * @private
         */
        function onCookieRedirectCheck( $type ) {
-               global $wgUser;
-
                if ( !$this->hasSessionCookie() ) {
                        if ( $type == 'new' ) {
                                return $this->mainLoginForm( wfMsgExt( 'nocookiesnew', array( 'parseinline' ) ) );
@@ -904,7 +1023,7 @@ class LoginForm {
                                return $this->mainLoginForm( wfMsg( 'error' ) );
                        }
                } else {
-                       return $this->successfulLogin( 'loginsuccess', $wgUser->getName() );
+                       return $this->successfulLogin();
                }
        }
 
@@ -912,9 +1031,7 @@ class LoginForm {
         * @private
         */
        function throttleHit( $limit ) {
-               global $wgOut;
-
-               $wgOut->addWikiMsg( 'acct_creation_throttle_hit', $limit );
+               $this->mainLoginForm( wfMsgExt( 'acct_creation_throttle_hit', array( 'parseinline' ), $limit ) );
        }
 
        /**
@@ -924,6 +1041,8 @@ class LoginForm {
         * @return string
         */
        function makeLanguageSelector() {
+               global $wgLang;
+
                $msg = wfMsgForContent( 'loginlanguagelinks' );
                if( $msg != '' && !wfEmptyMsg( 'loginlanguagelinks', $msg ) ) {
                        $langs = explode( "\n", $msg );
@@ -935,7 +1054,7 @@ class LoginForm {
                                        $links[] = $this->makeLanguageSelectorLink( $parts[0], $parts[1] );
                                }
                        }
-                       return count( $links ) > 0 ? wfMsgHtml( 'loginlanguagelabel', implode( ' | ', $links ) ) : '';
+                       return count( $links ) > 0 ? wfMsgHtml( 'loginlanguagelabel', $wgLang->pipeList( $links ) ) : '';
                } else {
                        return '';
                }
@@ -951,12 +1070,17 @@ class LoginForm {
        function makeLanguageSelectorLink( $text, $lang ) {
                global $wgUser;
                $self = SpecialPage::getTitleFor( 'Userlogin' );
-               $attr[] = 'uselang=' . $lang;
+               $attr = array( 'uselang' => $lang );
                if( $this->mType == 'signup' )
-                       $attr[] = 'type=signup';
+                       $attr['type'] = 'signup';
                if( $this->mReturnTo )
-                       $attr[] = 'returnto=' . $this->mReturnTo;
+                       $attr['returnto'] = $this->mReturnTo;
                $skin = $wgUser->getSkin();
-               return $skin->makeKnownLinkObj( $self, htmlspecialchars( $text ), implode( '&', $attr ) );
+               return $skin->linkKnown(
+                       $self,
+                       htmlspecialchars( $text ),
+                       array(),
+                       $attr
+               );
        }
 }