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