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