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