Merge "Follow-up I087c2729 (750936f): factorise common code"
[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->displaySuccessfulAction( $this->msg( 'loginsuccesstitle' ),
902 'loginsuccess', $injected_html );
903 } else {
904 $this->executeReturnTo( 'successredirect' );
905 }
906 }
907
908 /**
909 * Run any hooks registered for logins, then display a message welcoming
910 * the user.
911 *
912 * @private
913 */
914 function successfulCreation() {
915 # Run any hooks; display injected HTML
916 $currentUser = $this->getUser();
917 $injected_html = '';
918 $welcome_creation_msg = 'welcomecreation';
919
920 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
921
922 /**
923 * Let any extensions change what message is shown.
924 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
925 * @since 1.18
926 */
927 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
928
929 $this->displaySuccessfulAction( $this->msg( 'welcomeuser', $this->getUser()->getName() ),
930 $welcome_creation_msg, $injected_html );
931 }
932
933 /**
934 * Display an "successful action" page.
935 *
936 * @param $title string|Message page's title
937 * @param $msgname string
938 * @param $injected_html string
939 */
940 private function displaySuccessfulAction( $title, $msgname, $injected_html ) {
941 $out = $this->getOutput();
942 $out->setPageTitle( $title );
943 if ( $msgname ) {
944 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
945 }
946
947 $out->addHTML( $injected_html );
948
949 $this->executeReturnTo( 'success' );
950 }
951
952 /**
953 * Output a message that informs the user that they cannot create an account because
954 * there is a block on them or their IP which prevents account creation. Note that
955 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
956 * setting on blocks (bug 13611).
957 * @param $block Block the block causing this error
958 */
959 function userBlockedMessage( Block $block ) {
960 # Let's be nice about this, it's likely that this feature will be used
961 # for blocking large numbers of innocent people, e.g. range blocks on
962 # schools. Don't blame it on the user. There's a small chance that it
963 # really is the user's fault, i.e. the username is blocked and they
964 # haven't bothered to log out before trying to create an account to
965 # evade it, but we'll leave that to their guilty conscience to figure
966 # out.
967
968 $out = $this->getOutput();
969 $out->setPageTitle( $this->msg( 'cantcreateaccounttitle' ) );
970
971 $block_reason = $block->mReason;
972 if ( strval( $block_reason ) === '' ) {
973 $block_reason = $this->msg( 'blockednoreason' )->text();
974 }
975
976 $out->addWikiMsg(
977 'cantcreateaccount-text',
978 $block->getTarget(),
979 $block_reason,
980 $block->getByName()
981 );
982
983 $this->executeReturnTo( 'error' );
984 }
985
986 /**
987 * Add a "return to" link or redirect to it.
988 *
989 * @param $type string, one of the following:
990 * - error: display a return to link ignoring $wgRedirectOnLogin
991 * - success: display a return to link using $wgRedirectOnLogin if needed
992 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
993 */
994 private function executeReturnTo( $type ) {
995 global $wgRedirectOnLogin, $wgSecureLogin;
996
997 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
998 $returnTo = $wgRedirectOnLogin;
999 $returnToQuery = array();
1000 } else {
1001 $returnTo = $this->mReturnTo;
1002 $returnToQuery = wfCgiToArray( $this->mReturnToQuery );
1003 }
1004
1005 $returnToTitle = Title::newFromText( $returnTo );
1006 if ( !$returnToTitle ) {
1007 $returnToTitle = Title::newMainPage();
1008 }
1009
1010 if ( $wgSecureLogin && !$this->mStickHTTPS ) {
1011 $options = array( 'http' );
1012 $proto = PROTO_HTTP;
1013 } elseif( $wgSecureLogin ) {
1014 $options = array( 'https' );
1015 $proto = PROTO_HTTPS;
1016 } else {
1017 $options = array();
1018 $proto = PROTO_RELATIVE;
1019 }
1020
1021 if ( $type == 'successredirect' ) {
1022 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery, false, $proto );
1023 $this->getOutput()->redirect( $redirectUrl );
1024 } else {
1025 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery, null, $options );
1026 }
1027 }
1028
1029 /**
1030 * @private
1031 */
1032 function mainLoginForm( $msg, $msgtype = 'error' ) {
1033 global $wgEnableEmail, $wgEnableUserEmail;
1034 global $wgHiddenPrefs, $wgLoginLanguageSelector;
1035 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
1036 global $wgSecureLogin, $wgPasswordResetRoutes;
1037
1038 $titleObj = $this->getTitle();
1039 $user = $this->getUser();
1040
1041 if ( $this->mType == 'signup' ) {
1042 // Block signup here if in readonly. Keeps user from
1043 // going through the process (filling out data, etc)
1044 // and being informed later.
1045 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
1046 if ( count( $permErrors ) ) {
1047 throw new PermissionsError( 'createaccount', $permErrors );
1048 } elseif ( $user->isBlockedFromCreateAccount() ) {
1049 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1050 return;
1051 } elseif ( wfReadOnly() ) {
1052 throw new ReadOnlyError;
1053 }
1054 }
1055
1056 if ( $this->mUsername == '' ) {
1057 if ( $user->isLoggedIn() ) {
1058 $this->mUsername = $user->getName();
1059 } else {
1060 $this->mUsername = $this->getRequest()->getCookie( 'UserName' );
1061 }
1062 }
1063
1064 if ( $this->mType == 'signup' ) {
1065 $template = new UsercreateTemplate();
1066 $q = 'action=submitlogin&type=signup';
1067 $linkq = 'type=login';
1068 $linkmsg = 'gotaccount';
1069 } else {
1070 $template = new UserloginTemplate();
1071 $q = 'action=submitlogin&type=login';
1072 $linkq = 'type=signup';
1073 $linkmsg = 'nologin';
1074 }
1075
1076 if ( $this->mReturnTo !== '' ) {
1077 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
1078 if ( $this->mReturnToQuery !== '' ) {
1079 $returnto .= '&returntoquery=' .
1080 wfUrlencode( $this->mReturnToQuery );
1081 }
1082 $q .= $returnto;
1083 $linkq .= $returnto;
1084 }
1085
1086 # Don't show a "create account" link if the user can't
1087 if( $this->showCreateOrLoginLink( $user ) ) {
1088 # Pass any language selection on to the mode switch link
1089 if( $wgLoginLanguageSelector && $this->mLanguage ) {
1090 $linkq .= '&uselang=' . $this->mLanguage;
1091 }
1092 $link = Html::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
1093 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1094
1095 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1096 } else {
1097 $template->set( 'link', '' );
1098 }
1099
1100 $resetLink = $this->mType == 'signup'
1101 ? null
1102 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1103
1104 $template->set( 'header', '' );
1105 $template->set( 'name', $this->mUsername );
1106 $template->set( 'password', $this->mPassword );
1107 $template->set( 'retype', $this->mRetype );
1108 $template->set( 'email', $this->mEmail );
1109 $template->set( 'realname', $this->mRealName );
1110 $template->set( 'domain', $this->mDomain );
1111 $template->set( 'reason', $this->mReason );
1112
1113 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1114 $template->set( 'message', $msg );
1115 $template->set( 'messagetype', $msgtype );
1116 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1117 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1118 $template->set( 'useemail', $wgEnableEmail );
1119 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1120 $template->set( 'emailothers', $wgEnableUserEmail );
1121 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1122 $template->set( 'resetlink', $resetLink );
1123 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1124 $template->set( 'usereason', $user->isLoggedIn() );
1125 $template->set( 'remember', $user->getOption( 'rememberpassword' ) || $this->mRemember );
1126 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1127 $template->set( 'stickHTTPS', $this->mStickHTTPS );
1128
1129 if ( $this->mType == 'signup' ) {
1130 if ( !self::getCreateaccountToken() ) {
1131 self::setCreateaccountToken();
1132 }
1133 $template->set( 'token', self::getCreateaccountToken() );
1134 } else {
1135 if ( !self::getLoginToken() ) {
1136 self::setLoginToken();
1137 }
1138 $template->set( 'token', self::getLoginToken() );
1139 }
1140
1141 # Prepare language selection links as needed
1142 if( $wgLoginLanguageSelector ) {
1143 $template->set( 'languages', $this->makeLanguageSelector() );
1144 if( $this->mLanguage ) {
1145 $template->set( 'uselang', $this->mLanguage );
1146 }
1147 }
1148
1149 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1150 // Ditto for signupend
1151 $usingHTTPS = WebRequest::detectProtocol() == 'https';
1152 $loginendHTTPS = $this->msg( 'loginend-https' );
1153 $signupendHTTPS = $this->msg( 'signupend-https' );
1154 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1155 $template->set( 'loginend', $loginendHTTPS->parse() );
1156 } else {
1157 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1158 }
1159 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1160 $template->set( 'signupend', $signupendHTTPS->parse() );
1161 } else {
1162 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1163 }
1164
1165 // Give authentication and captcha plugins a chance to modify the form
1166 $wgAuth->modifyUITemplate( $template, $this->mType );
1167 if ( $this->mType == 'signup' ) {
1168 wfRunHooks( 'UserCreateForm', array( &$template ) );
1169 } else {
1170 wfRunHooks( 'UserLoginForm', array( &$template ) );
1171 }
1172
1173 $out = $this->getOutput();
1174 $out->disallowUserJs(); // just in case...
1175 $out->addTemplate( $template );
1176 }
1177
1178 /**
1179 * @private
1180 *
1181 * @param $user User
1182 *
1183 * @return Boolean
1184 */
1185 function showCreateOrLoginLink( &$user ) {
1186 if( $this->mType == 'signup' ) {
1187 return true;
1188 } elseif( $user->isAllowed( 'createaccount' ) ) {
1189 return true;
1190 } else {
1191 return false;
1192 }
1193 }
1194
1195 /**
1196 * Check if a session cookie is present.
1197 *
1198 * This will not pick up a cookie set during _this_ request, but is meant
1199 * to ensure that the client is returning the cookie which was set on a
1200 * previous pass through the system.
1201 *
1202 * @private
1203 * @return bool
1204 */
1205 function hasSessionCookie() {
1206 global $wgDisableCookieCheck;
1207 return $wgDisableCookieCheck ? true : $this->getRequest()->checkSessionCookie();
1208 }
1209
1210 /**
1211 * Get the login token from the current session
1212 * @return Mixed
1213 */
1214 public static function getLoginToken() {
1215 global $wgRequest;
1216 return $wgRequest->getSessionData( 'wsLoginToken' );
1217 }
1218
1219 /**
1220 * Randomly generate a new login token and attach it to the current session
1221 */
1222 public static function setLoginToken() {
1223 global $wgRequest;
1224 // Generate a token directly instead of using $user->editToken()
1225 // because the latter reuses $_SESSION['wsEditToken']
1226 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand::generateHex( 32 ) );
1227 }
1228
1229 /**
1230 * Remove any login token attached to the current session
1231 */
1232 public static function clearLoginToken() {
1233 global $wgRequest;
1234 $wgRequest->setSessionData( 'wsLoginToken', null );
1235 }
1236
1237 /**
1238 * Get the createaccount token from the current session
1239 * @return Mixed
1240 */
1241 public static function getCreateaccountToken() {
1242 global $wgRequest;
1243 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1244 }
1245
1246 /**
1247 * Randomly generate a new createaccount token and attach it to the current session
1248 */
1249 public static function setCreateaccountToken() {
1250 global $wgRequest;
1251 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand::generateHex( 32 ) );
1252 }
1253
1254 /**
1255 * Remove any createaccount token attached to the current session
1256 */
1257 public static function clearCreateaccountToken() {
1258 global $wgRequest;
1259 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1260 }
1261
1262 /**
1263 * @private
1264 */
1265 function cookieRedirectCheck( $type ) {
1266 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
1267 $query = array( 'wpCookieCheck' => $type );
1268 if ( $this->mReturnTo !== '' ) {
1269 $query['returnto'] = $this->mReturnTo;
1270 $query['returntoquery'] = $this->mReturnToQuery;
1271 }
1272 $check = $titleObj->getFullURL( $query );
1273
1274 $this->getOutput()->redirect( $check );
1275 }
1276
1277 /**
1278 * @private
1279 */
1280 function onCookieRedirectCheck( $type ) {
1281 if ( !$this->hasSessionCookie() ) {
1282 if ( $type == 'new' ) {
1283 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1284 } elseif ( $type == 'login' ) {
1285 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1286 } else {
1287 # shouldn't happen
1288 $this->mainLoginForm( $this->msg( 'error' )->text() );
1289 }
1290 } else {
1291 $this->successfulLogin();
1292 }
1293 }
1294
1295 /**
1296 * @private
1297 */
1298 function throttleHit( $limit ) {
1299 $this->mainLoginForm( $this->msg( 'acct_creation_throttle_hit' )->numParams( $limit )->parse() );
1300 }
1301
1302 /**
1303 * Produce a bar of links which allow the user to select another language
1304 * during login/registration but retain "returnto"
1305 *
1306 * @return string
1307 */
1308 function makeLanguageSelector() {
1309 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1310 if( !$msg->isBlank() ) {
1311 $langs = explode( "\n", $msg->text() );
1312 $links = array();
1313 foreach( $langs as $lang ) {
1314 $lang = trim( $lang, '* ' );
1315 $parts = explode( '|', $lang );
1316 if ( count( $parts ) >= 2 ) {
1317 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1318 }
1319 }
1320 return count( $links ) > 0 ? $this->msg( 'loginlanguagelabel' )->rawParams(
1321 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1322 } else {
1323 return '';
1324 }
1325 }
1326
1327 /**
1328 * Create a language selector link for a particular language
1329 * Links back to this page preserving type and returnto
1330 *
1331 * @param $text Link text
1332 * @param $lang Language code
1333 * @return string
1334 */
1335 function makeLanguageSelectorLink( $text, $lang ) {
1336 if( $this->getLanguage()->getCode() == $lang ) {
1337 // no link for currently used language
1338 return htmlspecialchars( $text );
1339 }
1340 $query = array( 'uselang' => $lang );
1341 if( $this->mType == 'signup' ) {
1342 $query['type'] = 'signup';
1343 }
1344 if( $this->mReturnTo !== '' ) {
1345 $query['returnto'] = $this->mReturnTo;
1346 $query['returntoquery'] = $this->mReturnToQuery;
1347 }
1348
1349 $attr = array();
1350 $targetLanguage = Language::factory( $lang );
1351 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1352
1353 return Linker::linkKnown(
1354 $this->getTitle(),
1355 htmlspecialchars( $text ),
1356 $attr,
1357 $query
1358 );
1359 }
1360 }