]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/specials/SpecialUserlogin.php
MediaWiki 1.15.3
[autoinstalls/mediawiki.git] / includes / specials / SpecialUserlogin.php
1 <?php
2 /**
3  * @file
4  * @ingroup SpecialPage
5  */
6
7 /**
8  * constructor
9  */
10 function wfSpecialUserlogin( $par = '' ) {
11         global $wgRequest;
12         if( session_id() == '' ) {
13                 wfSetupSession();
14         }
15
16         $form = new LoginForm( $wgRequest, $par );
17         $form->execute();
18 }
19
20 /**
21  * implements Special:Login
22  * @ingroup SpecialPage
23  */
24 class LoginForm {
25
26         const SUCCESS = 0;
27         const NO_NAME = 1;
28         const ILLEGAL = 2;
29         const WRONG_PLUGIN_PASS = 3;
30         const NOT_EXISTS = 4;
31         const WRONG_PASS = 5;
32         const EMPTY_PASS = 6;
33         const RESET_PASS = 7;
34         const ABORTED = 8;
35         const CREATE_BLOCKED = 9;
36         const THROTTLED = 10;
37         const USER_BLOCKED = 11;
38         const NEED_TOKEN = 12;
39         const WRONG_TOKEN = 13;
40
41         var $mName, $mPassword, $mRetype, $mReturnTo, $mCookieCheck, $mPosted;
42         var $mAction, $mCreateaccount, $mCreateaccountMail, $mMailmypassword;
43         var $mLoginattempt, $mRemember, $mEmail, $mDomain, $mLanguage, $mSkipCookieCheck;
44         var $mToken;
45
46         /**
47          * Constructor
48          * @param WebRequest $request A WebRequest object passed by reference
49          */
50         function LoginForm( &$request, $par = '' ) {
51                 global $wgLang, $wgAllowRealName, $wgEnableEmail;
52                 global $wgAuth, $wgRedirectOnLogin;
53
54                 $this->mType = ( $par == 'signup' ) ? $par : $request->getText( 'type' ); # Check for [[Special:Userlogin/signup]]
55                 $this->mName = $request->getText( 'wpName' );
56                 $this->mPassword = $request->getText( 'wpPassword' );
57                 $this->mRetype = $request->getText( 'wpRetype' );
58                 $this->mDomain = $request->getText( 'wpDomain' );
59                 $this->mReturnTo = $request->getVal( 'returnto' );
60                 $this->mCookieCheck = $request->getVal( 'wpCookieCheck' );
61                 $this->mPosted = $request->wasPosted();
62                 $this->mCreateaccount = $request->getCheck( 'wpCreateaccount' );
63                 $this->mCreateaccountMail = $request->getCheck( 'wpCreateaccountMail' )
64                                             && $wgEnableEmail;
65                 $this->mMailmypassword = $request->getCheck( 'wpMailmypassword' )
66                                          && $wgEnableEmail;
67                 $this->mLoginattempt = $request->getCheck( 'wpLoginattempt' );
68                 $this->mAction = $request->getVal( 'action' );
69                 $this->mRemember = $request->getCheck( 'wpRemember' );
70                 $this->mLanguage = $request->getText( 'uselang' );
71                 $this->mSkipCookieCheck = $request->getCheck( 'wpSkipCookieCheck' );
72                 $this->mToken = $request->getVal( 'wpLoginToken' );
73
74                 if ( $wgRedirectOnLogin ) {
75                         $this->mReturnTo = $wgRedirectOnLogin;
76                 }
77
78                 if( $wgEnableEmail ) {
79                         $this->mEmail = $request->getText( 'wpEmail' );
80                 } else {
81                         $this->mEmail = '';
82                 }
83                 if( $wgAllowRealName ) {
84                     $this->mRealName = $request->getText( 'wpRealName' );
85                 } else {
86                     $this->mRealName = '';
87                 }
88
89                 if( !$wgAuth->validDomain( $this->mDomain ) ) {
90                         $this->mDomain = 'invaliddomain';
91                 }
92                 $wgAuth->setDomain( $this->mDomain );
93
94                 # When switching accounts, it sucks to get automatically logged out
95                 if( $this->mReturnTo == $wgLang->specialPage( 'Userlogout' ) ) {
96                         $this->mReturnTo = '';
97                 }
98         }
99
100         function execute() {
101                 if ( !is_null( $this->mCookieCheck ) ) {
102                         $this->onCookieRedirectCheck( $this->mCookieCheck );
103                         return;
104                 } else if( $this->mPosted ) {
105                         if( $this->mCreateaccount ) {
106                                 return $this->addNewAccount();
107                         } else if ( $this->mCreateaccountMail ) {
108                                 return $this->addNewAccountMailPassword();
109                         } else if ( $this->mMailmypassword ) {
110                                 return $this->mailPassword();
111                         } else if ( ( 'submitlogin' == $this->mAction ) || $this->mLoginattempt ) {
112                                 return $this->processLogin();
113                         }
114                 }
115                 $this->mainLoginForm( '' );
116         }
117
118         /**
119          * @private
120          */
121         function addNewAccountMailPassword() {
122                 global $wgOut;
123
124                 if ('' == $this->mEmail) {
125                         $this->mainLoginForm( wfMsg( 'noemail', htmlspecialchars( $this->mName ) ) );
126                         return;
127                 }
128
129                 $u = $this->addNewaccountInternal();
130
131                 if ($u == NULL) {
132                         return;
133                 }
134
135                 // Wipe the initial password and mail a temporary one
136                 $u->setPassword( null );
137                 $u->saveSettings();
138                 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
139
140                 wfRunHooks( 'AddNewAccount', array( $u, true ) );
141                 $u->addNewUserLogEntry();
142
143                 $wgOut->setPageTitle( wfMsg( 'accmailtitle' ) );
144                 $wgOut->setRobotPolicy( 'noindex,nofollow' );
145                 $wgOut->setArticleRelated( false );
146
147                 if( WikiError::isError( $result ) ) {
148                         $this->mainLoginForm( wfMsg( 'mailerror', $result->getMessage() ) );
149                 } else {
150                         $wgOut->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
151                         $wgOut->returnToMain( false );
152                 }
153                 $u = 0;
154         }
155
156
157         /**
158          * @private
159          */
160         function addNewAccount() {
161                 global $wgUser, $wgEmailAuthentication;
162
163                 # Create the account and abort if there's a problem doing so
164                 $u = $this->addNewAccountInternal();
165                 if( $u == NULL )
166                         return;
167
168                 # If we showed up language selection links, and one was in use, be
169                 # smart (and sensible) and save that language as the user's preference
170                 global $wgLoginLanguageSelector;
171                 if( $wgLoginLanguageSelector && $this->mLanguage )
172                         $u->setOption( 'language', $this->mLanguage );
173
174                 # Send out an email authentication message if needed
175                 if( $wgEmailAuthentication && User::isValidEmailAddr( $u->getEmail() ) ) {
176                         global $wgOut;
177                         $error = $u->sendConfirmationMail();
178                         if( WikiError::isError( $error ) ) {
179                                 $wgOut->addWikiMsg( 'confirmemail_sendfailed', $error->getMessage() );
180                         } else {
181                                 $wgOut->addWikiMsg( 'confirmemail_oncreate' );
182                         }
183                 }
184
185                 # Save settings (including confirmation token)
186                 $u->saveSettings();
187
188                 # If not logged in, assume the new account as the current one and set
189                 # session cookies then show a "welcome" message or a "need cookies"
190                 # message as needed
191                 if( $wgUser->isAnon() ) {
192                         $wgUser = $u;
193                         $wgUser->setCookies();
194                         wfRunHooks( 'AddNewAccount', array( $wgUser ) );
195                         $wgUser->addNewUserLogEntry();
196                         if( $this->hasSessionCookie() ) {
197                                 return $this->successfulCreation();
198                         } else {
199                                 return $this->cookieRedirectCheck( 'new' );
200                         }
201                 } else {
202                         # Confirm that the account was created
203                         global $wgOut;
204                         $self = SpecialPage::getTitleFor( 'Userlogin' );
205                         $wgOut->setPageTitle( wfMsgHtml( 'accountcreated' ) );
206                         $wgOut->setArticleRelated( false );
207                         $wgOut->setRobotPolicy( 'noindex,nofollow' );
208                         $wgOut->addHTML( wfMsgWikiHtml( 'accountcreatedtext', $u->getName() ) );
209                         $wgOut->returnToMain( false, $self );
210                         wfRunHooks( 'AddNewAccount', array( $u ) );
211                         $u->addNewUserLogEntry();
212                         return true;
213                 }
214         }
215
216         /**
217          * @private
218          */
219         function addNewAccountInternal() {
220                 global $wgUser, $wgOut;
221                 global $wgEnableSorbs, $wgProxyWhitelist;
222                 global $wgMemc, $wgAccountCreationThrottle;
223                 global $wgAuth, $wgMinimalPasswordLength;
224                 global $wgEmailConfirmToEdit;
225
226                 // If the user passes an invalid domain, something is fishy
227                 if( !$wgAuth->validDomain( $this->mDomain ) ) {
228                         $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
229                         return false;
230                 }
231
232                 // If we are not allowing users to login locally, we should be checking
233                 // to see if the user is actually able to authenticate to the authenti-
234                 // cation server before they create an account (otherwise, they can
235                 // create a local account and login as any domain user). We only need
236                 // to check this for domains that aren't local.
237                 if( 'local' != $this->mDomain && '' != $this->mDomain ) {
238                         if( !$wgAuth->canCreateAccounts() && ( !$wgAuth->userExists( $this->mName ) || !$wgAuth->authenticate( $this->mName, $this->mPassword ) ) ) {
239                                 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
240                                 return false;
241                         }
242                 }
243
244                 if ( wfReadOnly() ) {
245                         $wgOut->readOnlyPage();
246                         return false;
247                 }
248
249                 # Check permissions
250                 if ( !$wgUser->isAllowed( 'createaccount' ) ) {
251                         $this->userNotPrivilegedMessage();
252                         return false;
253                 } elseif ( $wgUser->isBlockedFromCreateAccount() ) {
254                         $this->userBlockedMessage();
255                         return false;
256                 }
257
258                 $ip = wfGetIP();
259                 if ( $wgEnableSorbs && !in_array( $ip, $wgProxyWhitelist ) &&
260                   $wgUser->inSorbsBlacklist( $ip ) )
261                 {
262                         $this->mainLoginForm( wfMsg( 'sorbs_create_account_reason' ) . ' (' . htmlspecialchars( $ip ) . ')' );
263                         return;
264                 }
265
266                 # Now create a dummy user ($u) and check if it is valid
267                 $name = trim( $this->mName );
268                 $u = User::newFromName( $name, 'creatable' );
269                 if ( is_null( $u ) ) {
270                         $this->mainLoginForm( wfMsg( 'noname' ) );
271                         return false;
272                 }
273
274                 if ( 0 != $u->idForName() ) {
275                         $this->mainLoginForm( wfMsg( 'userexists' ) );
276                         return false;
277                 }
278
279                 if ( 0 != strcmp( $this->mPassword, $this->mRetype ) ) {
280                         $this->mainLoginForm( wfMsg( 'badretype' ) );
281                         return false;
282                 }
283
284                 # check for minimal password length
285                 if ( !$u->isValidPassword( $this->mPassword ) ) {
286                         if ( !$this->mCreateaccountMail ) {
287                                 $this->mainLoginForm( wfMsgExt( 'passwordtooshort', array( 'parsemag' ), $wgMinimalPasswordLength ) );
288                                 return false;
289                         } else {
290                                 # do not force a password for account creation by email
291                                 # set invalid password, it will be replaced later by a random generated password
292                                 $this->mPassword = null;
293                         }
294                 }
295
296                 # if you need a confirmed email address to edit, then obviously you
297                 # need an email address.
298                 if ( $wgEmailConfirmToEdit && empty( $this->mEmail ) ) {
299                         $this->mainLoginForm( wfMsg( 'noemailtitle' ) );
300                         return false;
301                 }
302
303                 if( !empty( $this->mEmail ) && !User::isValidEmailAddr( $this->mEmail ) ) {
304                         $this->mainLoginForm( wfMsg( 'invalidemailaddress' ) );
305                         return false;
306                 }
307
308                 # Set some additional data so the AbortNewAccount hook can be used for
309                 # more than just username validation
310                 $u->setEmail( $this->mEmail );
311                 $u->setRealName( $this->mRealName );
312
313                 $abortError = '';
314                 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
315                         // Hook point to add extra creation throttles and blocks
316                         wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
317                         $this->mainLoginForm( $abortError );
318                         return false;
319                 }
320
321                 if ( $wgAccountCreationThrottle && $wgUser->isPingLimitable() ) {
322                         $key = wfMemcKey( 'acctcreate', 'ip', $ip );
323                         $value = $wgMemc->get( $key );
324                         if ( !$value ) {
325                                 $wgMemc->set( $key, 0, 86400 );
326                         }
327                         if ( $value >= $wgAccountCreationThrottle ) {
328                                 $this->throttleHit( $wgAccountCreationThrottle );
329                                 return false;
330                         }
331                         $wgMemc->incr( $key );
332                 }
333
334                 if( !$wgAuth->addUser( $u, $this->mPassword, $this->mEmail, $this->mRealName ) ) {
335                         $this->mainLoginForm( wfMsg( 'externaldberror' ) );
336                         return false;
337                 }
338
339                 return $this->initUser( $u, false );
340         }
341
342         /**
343          * Actually add a user to the database.
344          * Give it a User object that has been initialised with a name.
345          *
346          * @param $u User object.
347          * @param $autocreate boolean -- true if this is an autocreation via auth plugin
348          * @return User object.
349          * @private
350          */
351         function initUser( $u, $autocreate ) {
352                 global $wgAuth;
353
354                 $u->addToDatabase();
355
356                 if ( $wgAuth->allowPasswordChange() ) {
357                         $u->setPassword( $this->mPassword );
358                 }
359
360                 $u->setEmail( $this->mEmail );
361                 $u->setRealName( $this->mRealName );
362                 $u->setToken();
363
364                 $wgAuth->initUser( $u, $autocreate );
365
366                 $u->setOption( 'rememberpassword', $this->mRemember ? 1 : 0 );
367                 $u->saveSettings();
368
369                 # Update user count
370                 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
371                 $ssUpdate->doUpdate();
372
373                 return $u;
374         }
375
376         /**
377          * Internally authenticate the login request.
378          *
379          * This may create a local account as a side effect if the
380          * authentication plugin allows transparent local account
381          * creation.
382          *
383          * @public
384          */
385         function authenticateUserData() {
386                 global $wgUser, $wgAuth;
387                 if ( '' == $this->mName ) {
388                         return self::NO_NAME;
389                 }
390
391                 // We require a login token to prevent login CSRF
392                 // Handle part of this before incrementing the throttle so
393                 // token-less login attempts don't count towards the throttle
394                 // but wrong-token attempts do.
395                 
396                 // If the user doesn't have a login token yet, set one.
397                 if ( !self::getLoginToken() ) {
398                         self::setLoginToken();
399                         return self::NEED_TOKEN;
400                 }
401                 // If the user didn't pass a login token, tell them we need one
402                 if ( !$this->mToken ) {
403                         return self::NEED_TOKEN;
404                 }
405
406                 global $wgPasswordAttemptThrottle;
407
408                 $throttleCount=0;
409                 if ( is_array($wgPasswordAttemptThrottle) ) {
410                         $throttleKey = wfMemcKey( 'password-throttle', wfGetIP(), md5( $this->mName ) );
411                         $count = $wgPasswordAttemptThrottle['count'];
412                         $period = $wgPasswordAttemptThrottle['seconds'];
413                         
414                         global $wgMemc;
415                         $throttleCount = $wgMemc->get($throttleKey);
416                         if ( !$throttleCount ) {
417                                 $wgMemc->add( $throttleKey, 1, $period ); // start counter
418                         } else if ( $throttleCount < $count ) {
419                                 $wgMemc->incr($throttleKey);
420                         } else if ( $throttleCount >= $count ) {
421                                 return self::THROTTLED;
422                         }
423                 }
424                 
425                 // Validate the login token
426                 if ( $this->mToken !== self::getLoginToken() ) {
427                         return self::WRONG_TOKEN;
428                 }
429
430                 // Load $wgUser now, and check to see if we're logging in as the same
431                 // name. This is necessary because loading $wgUser (say by calling
432                 // getName()) calls the UserLoadFromSession hook, which potentially
433                 // creates the user in the database. Until we load $wgUser, checking
434                 // for user existence using User::newFromName($name)->getId() below
435                 // will effectively be using stale data.
436                 if ( $wgUser->getName() === $this->mName ) {
437                         wfDebug( __METHOD__.": already logged in as {$this->mName}\n" );
438                         return self::SUCCESS;
439                 }
440                 $u = User::newFromName( $this->mName );
441                 if( is_null( $u ) || !User::isUsableName( $u->getName() ) ) {
442                         return self::ILLEGAL;
443                 }
444
445                 $isAutoCreated = false;
446                 if ( 0 == $u->getID() ) {
447                         $status = $this->attemptAutoCreate( $u );
448                         if ( $status !== self::SUCCESS ) {
449                                 return $status;
450                         } else {
451                                 $isAutoCreated = true;
452                         }
453                 } else {
454                         $u->load();
455                 }
456
457                 // Give general extensions, such as a captcha, a chance to abort logins
458                 $abort = self::ABORTED;
459                 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword, &$abort ) ) ) {
460                         return $abort;
461                 }
462
463                 if (!$u->checkPassword( $this->mPassword )) {
464                         if( $u->checkTemporaryPassword( $this->mPassword ) ) {
465                                 // The e-mailed temporary password should not be used for actu-
466                                 // al logins; that's a very sloppy habit, and insecure if an
467                                 // attacker has a few seconds to click "search" on someone's o-
468                                 // pen mail reader.
469                                 //
470                                 // Allow it to be used only to reset the password a single time
471                                 // to a new value, which won't be in the user's e-mail ar-
472                                 // chives.
473                                 //
474                                 // For backwards compatibility, we'll still recognize it at the
475                                 // login form to minimize surprises for people who have been
476                                 // logging in with a temporary password for some time.
477                                 //
478                                 // As a side-effect, we can authenticate the user's e-mail ad-
479                                 // dress if it's not already done, since the temporary password
480                                 // was sent via e-mail.
481                                 if( !$u->isEmailConfirmed() ) {
482                                         $u->confirmEmail();
483                                         $u->saveSettings();
484                                 }
485
486                                 // At this point we just return an appropriate code/ indicating
487                                 // that the UI should show a password reset form; bot inter-
488                                 // faces etc will probably just fail cleanly here.
489                                 $retval = self::RESET_PASS;
490                         } else {
491                                 $retval = '' == $this->mPassword ? self::EMPTY_PASS : self::WRONG_PASS;
492                         }
493                 } else {
494                         $wgAuth->updateUser( $u );
495                         $wgUser = $u;
496
497                         // Please reset throttle for successful logins, thanks!
498                         if($throttleCount) {
499                                 $wgMemc->delete($throttleKey);
500                         }
501
502                         if ( $isAutoCreated ) {
503                                 // Must be run after $wgUser is set, for correct new user log
504                                 wfRunHooks( 'AuthPluginAutoCreate', array( $wgUser ) );
505                         }
506
507                         $retval = self::SUCCESS;
508                 }
509                 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword, $retval ) );
510                 return $retval;
511         }
512
513         /**
514          * Attempt to automatically create a user on login. Only succeeds if there
515          * is an external authentication method which allows it.
516          * @return integer Status code
517          */
518         function attemptAutoCreate( $user ) {
519                 global $wgAuth, $wgUser;
520                 /**
521                  * If the external authentication plugin allows it, automatically cre-
522                  * ate a new account for users that are externally defined but have not
523                  * yet logged in.
524                  */
525                 if ( !$wgAuth->autoCreate() ) {
526                         return self::NOT_EXISTS;
527                 }
528                 if ( !$wgAuth->userExists( $user->getName() ) ) {
529                         wfDebug( __METHOD__.": user does not exist\n" );
530                         return self::NOT_EXISTS;
531                 }
532                 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword ) ) {
533                         wfDebug( __METHOD__.": \$wgAuth->authenticate() returned false, aborting\n" );
534                         return self::WRONG_PLUGIN_PASS;
535                 }
536                 if ( $wgUser->isBlockedFromCreateAccount() ) {
537                         wfDebug( __METHOD__.": user is blocked from account creation\n" );
538                         return self::CREATE_BLOCKED;
539                 }
540
541                 wfDebug( __METHOD__.": creating account\n" );
542                 $user = $this->initUser( $user, true );
543                 return self::SUCCESS;
544         }
545
546         function processLogin() {
547                 global $wgUser, $wgAuth;
548
549                 switch ($this->authenticateUserData())
550                 {
551                         case self::SUCCESS:
552                                 # We've verified now, update the real record
553                                 if( (bool)$this->mRemember != (bool)$wgUser->getOption( 'rememberpassword' ) ) {
554                                         $wgUser->setOption( 'rememberpassword', $this->mRemember ? 1 : 0 );
555                                         $wgUser->saveSettings();
556                                 } else {
557                                         $wgUser->invalidateCache();
558                                 }
559                                 $wgUser->setCookies();
560                                 self::clearLoginToken();
561
562                                 // Reset the throttle
563                                 $key = wfMemcKey( 'password-throttle', wfGetIP(), md5( $this->mName ) );
564                                 global $wgMemc;
565                                 $wgMemc->delete( $key );
566
567                                 if( $this->hasSessionCookie() || $this->mSkipCookieCheck ) {
568                                         /* Replace the language object to provide user interface in
569                                          * correct language immediately on this first page load.
570                                          */
571                                         global $wgLang, $wgRequest;
572                                         $code = $wgRequest->getVal( 'uselang', $wgUser->getOption( 'language' ) );
573                                         $wgLang = Language::factory( $code );
574                                         return $this->successfulLogin();
575                                 } else {
576                                         return $this->cookieRedirectCheck( 'login' );
577                                 }
578                                 break;
579                         
580                         case self::NEED_TOKEN:
581                         case self::WRONG_TOKEN:
582                                 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
583                                 break;
584                         case self::NO_NAME:
585                         case self::ILLEGAL:
586                                 $this->mainLoginForm( wfMsg( 'noname' ) );
587                                 break;
588                         case self::WRONG_PLUGIN_PASS:
589                                 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
590                                 break;
591                         case self::NOT_EXISTS:
592                                 if( $wgUser->isAllowed( 'createaccount' ) ){
593                                         $this->mainLoginForm( wfMsgWikiHtml( 'nosuchuser', htmlspecialchars( $this->mName ) ) );
594                                 } else {
595                                         $this->mainLoginForm( wfMsg( 'nosuchusershort', htmlspecialchars( $this->mName ) ) );
596                                 }
597                                 break;
598                         case self::WRONG_PASS:
599                                 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
600                                 break;
601                         case self::EMPTY_PASS:
602                                 $this->mainLoginForm( wfMsg( 'wrongpasswordempty' ) );
603                                 break;
604                         case self::RESET_PASS:
605                                 $this->resetLoginForm( wfMsg( 'resetpass_announce' ) );
606                                 break;
607                         case self::CREATE_BLOCKED:
608                                 $this->userBlockedMessage();
609                                 break;
610                         case self::THROTTLED:
611                                 $this->mainLoginForm( wfMsg( 'login-throttled' ) );
612                                 break;
613                         default:
614                                 throw new MWException( "Unhandled case value" );
615                 }
616         }
617
618         function resetLoginForm( $error ) {
619                 global $wgOut;
620                 $wgOut->addHTML( Xml::element('p', array( 'class' => 'error' ), $error ) );
621                 $reset = new SpecialResetpass();
622                 $reset->execute( null );
623         }
624
625         /**
626          * @private
627          */
628         function mailPassword() {
629                 global $wgUser, $wgOut, $wgAuth;
630                 
631                 if ( wfReadOnly() ) {
632                         $wgOut->readOnlyPage();
633                         return false;
634                 }
635                 
636                 if( !$wgAuth->allowPasswordChange() ) {
637                         $this->mainLoginForm( wfMsg( 'resetpass_forbidden' ) );
638                         return;
639                 }
640
641                 # Check against blocked IPs
642                 # fixme -- should we not?
643                 if( $wgUser->isBlocked() ) {
644                         $this->mainLoginForm( wfMsg( 'blocked-mailpassword' ) );
645                         return;
646                 }
647
648                 # Check against the rate limiter
649                 if( $wgUser->pingLimiter( 'mailpassword' ) ) {
650                         $wgOut->rateLimited();
651                         return;
652                 }
653
654                 if ( '' == $this->mName ) {
655                         $this->mainLoginForm( wfMsg( 'noname' ) );
656                         return;
657                 }
658                 $u = User::newFromName( $this->mName );
659                 if( is_null( $u ) ) {
660                         $this->mainLoginForm( wfMsg( 'noname' ) );
661                         return;
662                 }
663                 if ( 0 == $u->getID() ) {
664                         $this->mainLoginForm( wfMsgWikiHtml( 'nosuchuser', htmlspecialchars( $u->getName() ) ) );
665                         return;
666                 }
667
668                 # Check against password throttle
669                 if ( $u->isPasswordReminderThrottled() ) {
670                         global $wgPasswordReminderResendTime;
671                         # Round the time in hours to 3 d.p., in case someone is specifying
672                         # minutes or seconds.
673                         $this->mainLoginForm( wfMsgExt( 'throttled-mailpassword', array( 'parsemag' ),
674                                 round( $wgPasswordReminderResendTime, 3 ) ) );
675                         return;
676                 }
677
678                 $result = $this->mailPasswordInternal( $u, true, 'passwordremindertitle', 'passwordremindertext' );
679                 if( WikiError::isError( $result ) ) {
680                         $this->mainLoginForm( wfMsg( 'mailerror', $result->getMessage() ) );
681                 } else {
682                         $this->mainLoginForm( wfMsg( 'passwordsent', $u->getName() ), 'success' );
683                 }
684         }
685
686
687         /**
688          * @param object user
689          * @param bool throttle
690          * @param string message name of email title
691          * @param string message name of email text
692          * @return mixed true on success, WikiError on failure
693          * @private
694          */
695         function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
696                 global $wgServer, $wgScript, $wgUser, $wgNewPasswordExpiry;
697
698                 if ( '' == $u->getEmail() ) {
699                         return new WikiError( wfMsg( 'noemail', $u->getName() ) );
700                 }
701                 $ip = wfGetIP();
702                 if( !$ip ) {
703                         return new WikiError( wfMsg( 'badipaddress' ) );
704                 }
705                 
706                 wfRunHooks( 'User::mailPasswordInternal', array(&$wgUser, &$ip, &$u) );
707
708                 $np = $u->randomPassword();
709                 $u->setNewpassword( $np, $throttle );
710                 $u->saveSettings();
711
712                 $m = wfMsgExt( $emailText, array( 'parsemag' ), $ip, $u->getName(), $np,
713                                 $wgServer . $wgScript, round( $wgNewPasswordExpiry / 86400 ) );
714                 $result = $u->sendMail( wfMsg( $emailTitle ), $m );
715
716                 return $result;
717         }
718
719
720         /**
721          * Run any hooks registered for logins, then HTTP redirect to
722          * $this->mReturnTo (or Main Page if that's undefined).  Formerly we had a
723          * nice message here, but that's really not as useful as just being sent to
724          * wherever you logged in from.  It should be clear that the action was
725          * successful, given the lack of error messages plus the appearance of your
726          * name in the upper right.
727          *
728          * @private
729          */
730         function successfulLogin() {
731                 global $wgUser, $wgOut;
732
733                 # Run any hooks; display injected HTML if any, else redirect
734                 $injected_html = '';
735                 wfRunHooks('UserLoginComplete', array(&$wgUser, &$injected_html));
736
737                 if( $injected_html !== '' ) {
738                         $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
739                 } else {
740                         $titleObj = Title::newFromText( $this->mReturnTo );
741                         if ( !$titleObj instanceof Title ) {
742                                 $titleObj = Title::newMainPage();
743                         }
744
745                         $wgOut->redirect( $titleObj->getFullURL() );
746                 }
747         }
748
749         /**
750          * Run any hooks registered for logins, then display a message welcoming
751          * the user.
752          *
753          * @private
754          */
755         function successfulCreation() {
756                 global $wgUser, $wgOut;
757
758                 # Run any hooks; display injected HTML
759                 $injected_html = '';
760                 wfRunHooks('UserLoginComplete', array(&$wgUser, &$injected_html));
761
762                 $this->displaySuccessfulLogin( 'welcomecreation', $injected_html );
763         }
764
765         /**
766          * Display a "login successful" page.
767          */
768         private function displaySuccessfulLogin( $msgname, $injected_html ) {
769                 global $wgOut, $wgUser;
770
771                 $wgOut->setPageTitle( wfMsg( 'loginsuccesstitle' ) );
772                 $wgOut->setRobotPolicy( 'noindex,nofollow' );
773                 $wgOut->setArticleRelated( false );
774                 $wgOut->addWikiMsg( $msgname, $wgUser->getName() );
775                 $wgOut->addHTML( $injected_html );
776
777                 if ( !empty( $this->mReturnTo ) ) {
778                         $wgOut->returnToMain( null, $this->mReturnTo );
779                 } else {
780                         $wgOut->returnToMain( null );
781                 }
782         }
783
784         /** */
785         function userNotPrivilegedMessage($errors) {
786                 global $wgOut;
787
788                 $wgOut->setPageTitle( wfMsg( 'permissionserrors' ) );
789                 $wgOut->setRobotPolicy( 'noindex,nofollow' );
790                 $wgOut->setArticleRelated( false );
791
792                 $wgOut->addWikitext( $wgOut->formatPermissionsErrorMessage( $errors, 'createaccount' ) );
793                 // Stuff that might want to be added at the end. For example, instruc-
794                 // tions if blocked.
795                 $wgOut->addWikiMsg( 'cantcreateaccount-nonblock-text' );
796
797                 $wgOut->returnToMain( false );
798         }
799
800         /** */
801         function userBlockedMessage() {
802                 global $wgOut, $wgUser;
803
804                 # Let's be nice about this, it's likely that this feature will be used
805                 # for blocking large numbers of innocent people, e.g. range blocks on
806                 # schools. Don't blame it on the user. There's a small chance that it
807                 # really is the user's fault, i.e. the username is blocked and they
808                 # haven't bothered to log out before trying to create an account to
809                 # evade it, but we'll leave that to their guilty conscience to figure
810                 # out.
811
812                 $wgOut->setPageTitle( wfMsg( 'cantcreateaccounttitle' ) );
813                 $wgOut->setRobotPolicy( 'noindex,nofollow' );
814                 $wgOut->setArticleRelated( false );
815
816                 $ip = wfGetIP();
817                 $blocker = User::whoIs( $wgUser->mBlock->mBy );
818                 $block_reason = $wgUser->mBlock->mReason;
819
820                 if ( strval( $block_reason ) === '' ) {
821                         $block_reason = wfMsg( 'blockednoreason' );
822                 }
823                 $wgOut->addWikiMsg( 'cantcreateaccount-text', $ip, $block_reason, $blocker );
824                 $wgOut->returnToMain( false );
825         }
826
827         /**
828          * @private
829          */
830         function mainLoginForm( $msg, $msgtype = 'error' ) {
831                 global $wgUser, $wgOut, $wgAllowRealName, $wgEnableEmail;
832                 global $wgCookiePrefix, $wgLoginLanguageSelector;
833                 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
834                 
835                 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
836                 
837                 if ( $this->mType == 'signup' ) {
838                         // Block signup here if in readonly. Keeps user from 
839                         // going through the process (filling out data, etc) 
840                         // and being informed later.
841                         if ( wfReadOnly() ) {
842                                 $wgOut->readOnlyPage();
843                                 return;
844                         } elseif ( $wgUser->isBlockedFromCreateAccount() ) {
845                                 $this->userBlockedMessage();
846                                 return;
847                         } elseif ( count( $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $wgUser, true ) )>0 ) {
848                                 $wgOut->showPermissionsErrorPage( $permErrors, 'createaccount' );
849                                 return;
850                         }
851                 }
852
853                 if ( '' == $this->mName ) {
854                         if ( $wgUser->isLoggedIn() ) {
855                                 $this->mName = $wgUser->getName();
856                         } else {
857                                 $this->mName = isset( $_COOKIE[$wgCookiePrefix.'UserName'] ) ? $_COOKIE[$wgCookiePrefix.'UserName'] : null;
858                         }
859                 }
860
861                 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
862
863                 if ( $this->mType == 'signup' ) {
864                         $template = new UsercreateTemplate();
865                         $q = 'action=submitlogin&type=signup';
866                         $linkq = 'type=login';
867                         $linkmsg = 'gotaccount';
868                 } else {
869                         $template = new UserloginTemplate();
870                         $q = 'action=submitlogin&type=login';
871                         $linkq = 'type=signup';
872                         $linkmsg = 'nologin';
873                 }
874
875                 if ( !empty( $this->mReturnTo ) ) {
876                         $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
877                         $q .= $returnto;
878                         $linkq .= $returnto;
879                 }
880
881                 # Pass any language selection on to the mode switch link
882                 if( $wgLoginLanguageSelector && $this->mLanguage )
883                         $linkq .= '&uselang=' . $this->mLanguage;
884
885                 $link = '<a href="' . htmlspecialchars ( $titleObj->getLocalUrl( $linkq ) ) . '">';
886                 $link .= wfMsgHtml( $linkmsg . 'link' ); # Calling either 'gotaccountlink' or 'nologinlink'
887                 $link .= '</a>';
888
889                 # Don't show a "create account" link if the user can't
890                 if( $this->showCreateOrLoginLink( $wgUser ) )
891                         $template->set( 'link', wfMsgHtml( $linkmsg, $link ) );
892                 else
893                         $template->set( 'link', '' );
894
895                 $template->set( 'header', '' );
896                 $template->set( 'name', $this->mName );
897                 $template->set( 'password', $this->mPassword );
898                 $template->set( 'retype', $this->mRetype );
899                 $template->set( 'email', $this->mEmail );
900                 $template->set( 'realname', $this->mRealName );
901                 $template->set( 'domain', $this->mDomain );
902
903                 $template->set( 'action', $titleObj->getLocalUrl( $q ) );
904                 $template->set( 'message', $msg );
905                 $template->set( 'messagetype', $msgtype );
906                 $template->set( 'createemail', $wgEnableEmail && $wgUser->isLoggedIn() );
907                 $template->set( 'userealname', $wgAllowRealName );
908                 $template->set( 'useemail', $wgEnableEmail );
909                 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
910                 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
911                 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
912                 $template->set( 'remember', $wgUser->getOption( 'rememberpassword' ) or $this->mRemember  );
913
914                 if ( !self::getLoginToken() ) {
915                         self::setLoginToken();
916                 }
917                 $template->set( 'token', self::getLoginToken() );
918
919                 # Prepare language selection links as needed
920                 if( $wgLoginLanguageSelector ) {
921                         $template->set( 'languages', $this->makeLanguageSelector() );
922                         if( $this->mLanguage )
923                                 $template->set( 'uselang', $this->mLanguage );
924                 }
925
926                 // Give authentication and captcha plugins a chance to modify the form
927                 $wgAuth->modifyUITemplate( $template );
928                 if ( $this->mType == 'signup' ) {
929                         wfRunHooks( 'UserCreateForm', array( &$template ) );
930                 } else {
931                         wfRunHooks( 'UserLoginForm', array( &$template ) );
932                 }
933
934                 $wgOut->setPageTitle( wfMsg( 'userlogin' ) );
935                 $wgOut->setRobotPolicy( 'noindex,nofollow' );
936                 $wgOut->setArticleRelated( false );
937                 $wgOut->disallowUserJs();  // just in case...
938                 $wgOut->addTemplate( $template );
939         }
940
941         /**
942          * @private
943          */
944         function showCreateOrLoginLink( &$user ) {
945                 if( $this->mType == 'signup' ) {
946                         return( true );
947                 } elseif( $user->isAllowed( 'createaccount' ) ) {
948                         return( true );
949                 } else {
950                         return( false );
951                 }
952         }
953
954         /**
955          * Check if a session cookie is present.
956          *
957          * This will not pick up a cookie set during _this_ request, but is meant
958          * to ensure that the client is returning the cookie which was set on a
959          * previous pass through the system.
960          *
961          * @private
962          */
963         function hasSessionCookie() {
964                 global $wgDisableCookieCheck, $wgRequest;
965                 return $wgDisableCookieCheck ? true : $wgRequest->checkSessionCookie();
966         }
967         
968         /**
969          * Get the login token from the current session
970          */
971         public static function getLoginToken() {
972                 global $wgRequest;
973                 return $wgRequest->getSessionData( 'wsLoginToken' );
974         }
975         
976         /**
977          * Generate a new login token and attach it to the current session
978          */
979         public static function setLoginToken() {
980                 global $wgRequest;
981                 // Use User::generateToken() instead of $user->editToken()
982                 // because the latter reuses $_SESSION['wsEditToken']
983                 $wgRequest->setSessionData( 'wsLoginToken', User::generateToken() );
984         }
985         
986         /**
987          * Remove any login token attached to the current session
988          */
989         public static  function clearLoginToken() {
990                 global $wgRequest;
991                 $wgRequest->setSessionData( 'wsLoginToken', null );
992         }
993
994         /**
995          * @private
996          */
997         function cookieRedirectCheck( $type ) {
998                 global $wgOut;
999
1000                 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
1001                 $query = array( 'wpCookieCheck' => $type );
1002                 if ( $this->mReturnTo ) $query['returnto'] = $this->mReturnTo;
1003                 $check = $titleObj->getFullURL( $query );
1004
1005                 return $wgOut->redirect( $check );
1006         }
1007
1008         /**
1009          * @private
1010          */
1011         function onCookieRedirectCheck( $type ) {
1012                 global $wgUser;
1013
1014                 if ( !$this->hasSessionCookie() ) {
1015                         if ( $type == 'new' ) {
1016                                 return $this->mainLoginForm( wfMsgExt( 'nocookiesnew', array( 'parseinline' ) ) );
1017                         } else if ( $type == 'login' ) {
1018                                 return $this->mainLoginForm( wfMsgExt( 'nocookieslogin', array( 'parseinline' ) ) );
1019                         } else {
1020                                 # shouldn't happen
1021                                 return $this->mainLoginForm( wfMsg( 'error' ) );
1022                         }
1023                 } else {
1024                         return $this->successfulLogin();
1025                 }
1026         }
1027
1028         /**
1029          * @private
1030          */
1031         function throttleHit( $limit ) {
1032                 $this->mainLoginForm( wfMsgExt( 'acct_creation_throttle_hit', array( 'parseinline' ), $limit ) );
1033         }
1034
1035         /**
1036          * Produce a bar of links which allow the user to select another language
1037          * during login/registration but retain "returnto"
1038          *
1039          * @return string
1040          */
1041         function makeLanguageSelector() {
1042                 global $wgLang;
1043
1044                 $msg = wfMsgForContent( 'loginlanguagelinks' );
1045                 if( $msg != '' && !wfEmptyMsg( 'loginlanguagelinks', $msg ) ) {
1046                         $langs = explode( "\n", $msg );
1047                         $links = array();
1048                         foreach( $langs as $lang ) {
1049                                 $lang = trim( $lang, '* ' );
1050                                 $parts = explode( '|', $lang );
1051                                 if (count($parts) >= 2) {
1052                                         $links[] = $this->makeLanguageSelectorLink( $parts[0], $parts[1] );
1053                                 }
1054                         }
1055                         return count( $links ) > 0 ? wfMsgHtml( 'loginlanguagelabel', $wgLang->pipeList( $links ) ) : '';
1056                 } else {
1057                         return '';
1058                 }
1059         }
1060
1061         /**
1062          * Create a language selector link for a particular language
1063          * Links back to this page preserving type and returnto
1064          *
1065          * @param $text Link text
1066          * @param $lang Language code
1067          */
1068         function makeLanguageSelectorLink( $text, $lang ) {
1069                 global $wgUser;
1070                 $self = SpecialPage::getTitleFor( 'Userlogin' );
1071                 $attr[] = 'uselang=' . $lang;
1072                 if( $this->mType == 'signup' )
1073                         $attr[] = 'type=signup';
1074                 if( $this->mReturnTo )
1075                         $attr[] = 'returnto=' . $this->mReturnTo;
1076                 $skin = $wgUser->getSkin();
1077                 return $skin->makeKnownLinkObj( $self, htmlspecialchars( $text ), implode( '&', $attr ) );
1078         }
1079 }