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