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