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