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