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