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