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