Per Nikerabbit, follow-up to r59761: just check for "instanceof User"
[lhc/web/wiklou.git] / includes / specials / SpecialUserlogin.php
index a7d80df..6d1a2d9 100644 (file)
@@ -37,15 +37,17 @@ class LoginForm {
 
        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 +55,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 +69,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 +91,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 = '';
                }
        }
 
@@ -182,7 +192,7 @@ class LoginForm {
                if( $wgUser->isAnon() ) {
                        $wgUser = $u;
                        $wgUser->setCookies();
-                       wfRunHooks( 'AddNewAccount', array( $wgUser ) );
+                       wfRunHooks( 'AddNewAccount', array( $wgUser, false ) );
                        $wgUser->addNewUserLogEntry();
                        if( $this->hasSessionCookie() ) {
                                return $this->successfulCreation();
@@ -196,9 +206,9 @@ 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;
                }
@@ -257,7 +267,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 ( !$u instanceof User ) {
                        $this->mainLoginForm( wfMsg( 'noname' ) );
                        return false;
                }
@@ -273,9 +288,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
@@ -311,14 +327,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 ) ) {
@@ -353,6 +370,14 @@ class LoginForm {
 
                $wgAuth->initUser( $u, $autocreate );
 
+               if ( $this->mExtUser ) {
+                       $this->mExtUser->link( $u->getId() );
+                       $email = $this->mExtUser->getPref( 'emailaddress' );
+                       if ( $email && !$this->mEmail ) {
+                               $u->setEmail( $email );
+                       }
+               }
+
                $u->setOption( 'rememberpassword', $this->mRemember ? 1 : 0 );
                $u->saveSettings();
 
@@ -379,18 +404,20 @@ class LoginForm {
                }
                
                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;
                        }
                }
@@ -405,6 +432,11 @@ class LoginForm {
                        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;
@@ -462,6 +494,11 @@ class LoginForm {
                        $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 ) );
@@ -479,26 +516,40 @@ class LoginForm {
         * @return integer Status code
         */
        function attemptAutoCreate( $user ) {
-               global $wgAuth, $wgUser;
+               global $wgAuth, $wgUser, $wgAutocreatePolicy;
+
+               if ( $wgUser->isBlockedFromCreateAccount() ) {
+                       wfDebug( __METHOD__.": user is blocked from account creation\n" );
+                       return self::CREATE_BLOCKED;
+               }
+
                /**
                 * 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 ( !$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;
-               }
-               if ( $wgUser->isBlockedFromCreateAccount() ) {
-                       wfDebug( __METHOD__.": user is blocked from account creation\n" );
-                       return self::CREATE_BLOCKED;
+               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" );
@@ -509,8 +560,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' ) ) {
@@ -575,8 +625,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 );
        }
 
@@ -585,7 +635,12 @@ class LoginForm {
         */
        function mailPassword() {
                global $wgUser, $wgOut, $wgAuth;
-
+               
+               if ( wfReadOnly() ) {
+                       $wgOut->readOnlyPage();
+                       return false;
+               }
+               
                if( !$wgAuth->allowPasswordChange() ) {
                        $this->mainLoginForm( wfMsg( 'resetpass_forbidden' ) );
                        return;
@@ -597,6 +652,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' ) ) {
@@ -614,7 +676,7 @@ class LoginForm {
                        return;
                }
                if ( 0 == $u->getID() ) {
-                       $this->mainLoginForm( wfMsg( 'nosuchuser', $u->getName() ) );
+                       $this->mainLoginForm( wfMsgWikiHtml( 'nosuchuser', htmlspecialchars( $u->getName() ) ) );
                        return;
                }
 
@@ -646,8 +708,7 @@ 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() ) {
                        return new WikiError( wfMsg( 'noemail', $u->getName() ) );
@@ -663,7 +724,8 @@ class LoginForm {
                $u->setNewpassword( $np, $throttle );
                $u->saveSettings();
 
-               $m = wfMsg( $emailText, $ip, $u->getName(), $np, $wgServer . $wgScript );
+               $m = wfMsgExt( $emailText, array( 'parsemag' ), $ip, $u->getName(), $np,
+                               $wgServer . $wgScript, round( $wgNewPasswordExpiry / 86400 ) );
                $result = $u->sendMail( wfMsg( $emailTitle ), $m );
 
                return $result;
@@ -694,8 +756,7 @@ class LoginForm {
                        if ( !$titleObj instanceof Title ) {
                                $titleObj = Title::newMainPage();
                        }
-
-                       $wgOut->redirect( $titleObj->getFullURL() );
+                       $wgOut->redirect( $titleObj->getFullURL( $this->mReturnToQuery ) );
                }
        }
 
@@ -725,10 +786,10 @@ class LoginForm {
                $wgOut->setRobotPolicy( 'noindex,nofollow' );
                $wgOut->setArticleRelated( false );
                $wgOut->addWikiMsg( $msgname, $wgUser->getName() );
-               $wgOut->addHtml( $injected_html );
+               $wgOut->addHTML( $injected_html );
 
                if ( !empty( $this->mReturnTo ) ) {
-                       $wgOut->returnToMain( null, $this->mReturnTo );
+                       $wgOut->returnToMain( null, $this->mReturnTo, $this->mReturnToQuery );
                } else {
                        $wgOut->returnToMain( null );
                }
@@ -781,8 +842,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' );
@@ -827,6 +888,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;
                }
@@ -841,7 +905,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', '' );
 
@@ -857,7 +921,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() );
@@ -872,7 +936,7 @@ 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 {
@@ -920,7 +984,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 );
        }
@@ -929,8 +995,6 @@ class LoginForm {
         * @private
         */
        function onCookieRedirectCheck( $type ) {
-               global $wgUser;
-
                if ( !$this->hasSessionCookie() ) {
                        if ( $type == 'new' ) {
                                return $this->mainLoginForm( wfMsgExt( 'nocookiesnew', array( 'parseinline' ) ) );
@@ -959,6 +1023,8 @@ class LoginForm {
         * @return string
         */
        function makeLanguageSelector() {
+               global $wgLang;
+
                $msg = wfMsgForContent( 'loginlanguagelinks' );
                if( $msg != '' && !wfEmptyMsg( 'loginlanguagelinks', $msg ) ) {
                        $langs = explode( "\n", $msg );
@@ -970,7 +1036,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 '';
                }
@@ -986,12 +1052,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
+               );
        }
 }