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