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