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