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