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