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