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