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