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