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