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