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