Merge "Http::getProxy() method to get proxy configuration"
[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 return $status;
694 }
695
696 if ( $wgAuth->allowPasswordChange() ) {
697 $u->setPassword( $this->mPassword );
698 }
699
700 $u->setEmail( $this->mEmail );
701 $u->setRealName( $this->mRealName );
702 $u->setToken();
703
704 Hooks::run( 'LocalUserCreated', [ $u, $autocreate ] );
705 $oldUser = $u;
706 $wgAuth->initUser( $u, $autocreate );
707 if ( $oldUser !== $u ) {
708 wfWarn( get_class( $wgAuth ) . '::initUser() replaced the user object' );
709 }
710
711 $u->saveSettings();
712
713 // Update user count
714 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
715
716 // Watch user's userpage and talk page
717 $u->addWatch( $u->getUserPage(), User::IGNORE_USER_RIGHTS );
718
719 return Status::newGood( $u );
720 }
721
722 /**
723 * Internally authenticate the login request.
724 *
725 * This may create a local account as a side effect if the
726 * authentication plugin allows transparent local account
727 * creation.
728 * @return int
729 */
730 public function authenticateUserData() {
731 global $wgUser, $wgAuth;
732
733 $this->load();
734
735 if ( $this->mUsername == '' ) {
736 return self::NO_NAME;
737 }
738
739 // We require a login token to prevent login CSRF
740 // Handle part of this before incrementing the throttle so
741 // token-less login attempts don't count towards the throttle
742 // but wrong-token attempts do.
743
744 // If the user doesn't have a login token yet, set one.
745 $token = self::getLoginToken();
746 if ( $token->wasNew() ) {
747 return self::NEED_TOKEN;
748 }
749 // If the user didn't pass a login token, tell them we need one
750 if ( !$this->mToken ) {
751 return self::NEED_TOKEN;
752 }
753
754 $throttleCount = self::incrementLoginThrottle( $this->mUsername );
755 if ( $throttleCount ) {
756 $this->mThrottleWait = $throttleCount['wait'];
757 return self::THROTTLED;
758 }
759
760 // Validate the login token
761 if ( !$token->match( $this->mToken ) ) {
762 return self::WRONG_TOKEN;
763 }
764
765 // Load the current user now, and check to see if we're logging in as
766 // the same name. This is necessary because loading the current user
767 // (say by calling getName()) calls the UserLoadFromSession hook, which
768 // potentially creates the user in the database. Until we load $wgUser,
769 // checking for user existence using User::newFromName($name)->getId() below
770 // will effectively be using stale data.
771 if ( $this->getUser()->getName() === $this->mUsername ) {
772 wfDebug( __METHOD__ . ": already logged in as {$this->mUsername}\n" );
773
774 return self::SUCCESS;
775 }
776
777 $u = User::newFromName( $this->mUsername );
778 if ( $u === false ) {
779 return self::ILLEGAL;
780 }
781
782 $msg = null;
783 // Give extensions a way to indicate the username has been updated,
784 // rather than telling the user the account doesn't exist.
785 if ( !Hooks::run( 'LoginUserMigrated', [ $u, &$msg ] ) ) {
786 $this->mAbortLoginErrorMsg = $msg;
787 return self::USER_MIGRATED;
788 }
789
790 if ( !User::isUsableName( $u->getName() ) ) {
791 return self::ILLEGAL;
792 }
793
794 $isAutoCreated = false;
795 if ( $u->getId() == 0 ) {
796 $status = $this->attemptAutoCreate( $u );
797 if ( $status !== self::SUCCESS ) {
798 return $status;
799 } else {
800 $isAutoCreated = true;
801 }
802 } else {
803 $u->load();
804 }
805
806 // Give general extensions, such as a captcha, a chance to abort logins
807 $abort = self::ABORTED;
808 if ( !Hooks::run( 'AbortLogin', [ $u, $this->mPassword, &$abort, &$msg ] ) ) {
809 if ( !in_array( $abort, array_keys( self::$statusCodes ), true ) ) {
810 throw new Exception( 'Invalid status code returned from AbortLogin hook: ' . $abort );
811 }
812 $this->mAbortLoginErrorMsg = $msg;
813 return $abort;
814 }
815
816 global $wgBlockDisablesLogin;
817 if ( !$u->checkPassword( $this->mPassword ) ) {
818 if ( $u->checkTemporaryPassword( $this->mPassword ) ) {
819 /**
820 * The e-mailed temporary password should not be used for actu-
821 * al logins; that's a very sloppy habit, and insecure if an
822 * attacker has a few seconds to click "search" on someone's
823 * open mail reader.
824 *
825 * Allow it to be used only to reset the password a single time
826 * to a new value, which won't be in the user's e-mail ar-
827 * chives.
828 *
829 * For backwards compatibility, we'll still recognize it at the
830 * login form to minimize surprises for people who have been
831 * logging in with a temporary password for some time.
832 *
833 * As a side-effect, we can authenticate the user's e-mail ad-
834 * dress if it's not already done, since the temporary password
835 * was sent via e-mail.
836 */
837 if ( !$u->isEmailConfirmed() && !wfReadOnly() ) {
838 $u->confirmEmail();
839 $u->saveSettings();
840 }
841
842 // At this point we just return an appropriate code/ indicating
843 // that the UI should show a password reset form; bot inter-
844 // faces etc will probably just fail cleanly here.
845 $this->mAbortLoginErrorMsg = 'resetpass-temp-emailed';
846 $this->mTempPasswordUsed = true;
847 $retval = self::RESET_PASS;
848 } else {
849 $retval = ( $this->mPassword == '' ) ? self::EMPTY_PASS : self::WRONG_PASS;
850 }
851 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
852 // If we've enabled it, make it so that a blocked user cannot login
853 $retval = self::USER_BLOCKED;
854 } elseif ( $this->checkUserPasswordExpired( $u ) == 'hard' ) {
855 // Force reset now, without logging in
856 $retval = self::RESET_PASS;
857 $this->mAbortLoginErrorMsg = 'resetpass-expired';
858 } else {
859 Hooks::run( 'UserLoggedIn', [ $u ] );
860 $oldUser = $u;
861 $wgAuth->updateUser( $u );
862 if ( $oldUser !== $u ) {
863 wfWarn( get_class( $wgAuth ) . '::updateUser() replaced the user object' );
864 }
865 $wgUser = $u;
866 // This should set it for OutputPage and the Skin
867 // which is needed or the personal links will be
868 // wrong.
869 $this->getContext()->setUser( $u );
870
871 // Please reset throttle for successful logins, thanks!
872 self::clearLoginThrottle( $this->mUsername );
873
874 if ( $isAutoCreated ) {
875 // Must be run after $wgUser is set, for correct new user log
876 Hooks::run( 'AuthPluginAutoCreate', [ $u ] );
877 }
878
879 $retval = self::SUCCESS;
880 }
881 Hooks::run( 'LoginAuthenticateAudit', [ $u, $this->mPassword, $retval ] );
882
883 return $retval;
884 }
885
886 /**
887 * Increment the login attempt throttle hit count for the (username,current IP)
888 * tuple unless the throttle was already reached.
889 *
890 * @since 1.27 Return value changed.
891 * @param string $username The user name
892 * @return bool|array false if below limit or an array if above limit
893 * Array contains keys wait, count, and throttleIndex
894 */
895 public static function incrementLoginThrottle( $username ) {
896 global $wgPasswordAttemptThrottle, $wgRequest;
897 $username = User::getCanonicalName( $username, 'usable' ) ?: $username;
898
899 $throttleCount = 0;
900 if ( is_array( $wgPasswordAttemptThrottle ) ) {
901 $throttleConfig = $wgPasswordAttemptThrottle;
902 if ( isset( $wgPasswordAttemptThrottle['count'] ) ) {
903 // old style. Convert for backwards compat.
904 $throttleConfig = [ $wgPasswordAttemptThrottle ];
905 }
906 foreach ( $throttleConfig as $index => $specificThrottle ) {
907 if ( isset( $specificThrottle['allIPs'] ) ) {
908 $ip = 'All';
909 } else {
910 $ip = $wgRequest->getIP();
911 }
912 $throttleKey = wfGlobalCacheKey( 'password-throttle',
913 $index, $ip, md5( $username )
914 );
915 $count = $specificThrottle['count'];
916 $period = $specificThrottle['seconds'];
917
918 $cache = ObjectCache::getLocalClusterInstance();
919 $throttleCount = $cache->get( $throttleKey );
920 if ( !$throttleCount ) {
921 $cache->add( $throttleKey, 1, $period ); // start counter
922 } elseif ( $throttleCount < $count ) {
923 $cache->incr( $throttleKey );
924 } elseif ( $throttleCount >= $count ) {
925 $logMsg = 'Login attempt rejected because logins to '
926 . '{acct} from IP {ip} have been throttled for '
927 . '{period} seconds due to {count} failed attempts';
928 // If we are hitting a throttle for >= 50 attempts,
929 // it is much more likely to be an attack than someone
930 // simply forgetting their password, so log it at a
931 // higher level.
932 $level = $count >= 50 ? LogLevel::WARNING : LogLevel::INFO;
933 // It should be noted that once the throttle is hit,
934 // every attempt to login will generate the log message
935 // until the throttle expires, not just the attempt that
936 // puts the throttle over the top.
937 LoggerFactory::getInstance( 'password-throttle' )->log(
938 $level,
939 $logMsg,
940 [
941 'ip' => $ip,
942 'period' => $period,
943 'acct' => $username,
944 'count' => $count,
945 'throttleIdentifier' => $index,
946 'method' => __METHOD__
947 ]
948 );
949
950 return [
951 'throttleIndex' => $index,
952 'wait' => $period,
953 'count' => $count
954 ];
955 }
956 }
957 }
958 return false;
959 }
960
961 /**
962 * Increment the login attempt throttle hit count for the (username,current IP)
963 * tuple unless the throttle was already reached.
964 *
965 * @deprecated Use LoginForm::incrementLoginThrottle instead
966 * @param string $username The user name
967 * @return bool|int true if above throttle, or 0 (prior to 1.27, returned current count)
968 */
969 public static function incLoginThrottle( $username ) {
970 wfDeprecated( __METHOD__, "1.27" );
971 $res = self::incrementLoginThrottle( $username );
972 return is_array( $res ) ? true : 0;
973 }
974
975 /**
976 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
977 * @param string $username The user name
978 * @return void
979 */
980 public static function clearLoginThrottle( $username ) {
981 global $wgRequest, $wgPasswordAttemptThrottle;
982 $username = User::getCanonicalName( $username, 'usable' ) ?: $username;
983
984 if ( is_array( $wgPasswordAttemptThrottle ) ) {
985 $throttleConfig = $wgPasswordAttemptThrottle;
986 if ( isset( $wgPasswordAttemptThrottle['count'] ) ) {
987 // old style. Convert for backwards compat.
988 $throttleConfig = [ $wgPasswordAttemptThrottle ];
989 }
990 foreach ( $throttleConfig as $index => $specificThrottle ) {
991 if ( isset( $specificThrottle['allIPs'] ) ) {
992 $ip = 'All';
993 } else {
994 $ip = $wgRequest->getIP();
995 }
996 $throttleKey = wfGlobalCacheKey( 'password-throttle', $index,
997 $ip, md5( $username )
998 );
999 ObjectCache::getLocalClusterInstance()->delete( $throttleKey );
1000 }
1001 }
1002 }
1003
1004 /**
1005 * Attempt to automatically create a user on login. Only succeeds if there
1006 * is an external authentication method which allows it.
1007 *
1008 * @param User $user
1009 *
1010 * @return int Status code
1011 */
1012 function attemptAutoCreate( $user ) {
1013 global $wgAuth;
1014
1015 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
1016 wfDebug( __METHOD__ . ": user is blocked from account creation\n" );
1017
1018 return self::CREATE_BLOCKED;
1019 }
1020
1021 if ( !$wgAuth->autoCreate() ) {
1022 return self::NOT_EXISTS;
1023 }
1024
1025 if ( !$wgAuth->userExists( $user->getName() ) ) {
1026 wfDebug( __METHOD__ . ": user does not exist\n" );
1027
1028 return self::NOT_EXISTS;
1029 }
1030
1031 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword ) ) {
1032 wfDebug( __METHOD__ . ": \$wgAuth->authenticate() returned false, aborting\n" );
1033
1034 return self::WRONG_PLUGIN_PASS;
1035 }
1036
1037 $abortError = '';
1038 if ( !Hooks::run( 'AbortAutoAccount', [ $user, &$abortError ] ) ) {
1039 // Hook point to add extra creation throttles and blocks
1040 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
1041 $this->mAbortLoginErrorMsg = $abortError;
1042
1043 return self::ABORTED;
1044 }
1045
1046 wfDebug( __METHOD__ . ": creating account\n" );
1047 $status = $this->initUser( $user, true );
1048
1049 if ( !$status->isOK() ) {
1050 $errors = $status->getErrorsByType( 'error' );
1051 $this->mAbortLoginErrorMsg = $errors[0]['message'];
1052
1053 return self::ABORTED;
1054 }
1055
1056 return self::SUCCESS;
1057 }
1058
1059 function processLogin() {
1060 global $wgLang, $wgSecureLogin, $wgInvalidPasswordReset;
1061
1062 $cache = ObjectCache::getLocalClusterInstance();
1063 $authRes = $this->authenticateUserData();
1064 switch ( $authRes ) {
1065 case self::SUCCESS:
1066 # We've verified now, update the real record
1067 $user = $this->getUser();
1068 $user->touch();
1069
1070 if ( $user->requiresHTTPS() ) {
1071 $this->mStickHTTPS = true;
1072 }
1073
1074 if ( $wgSecureLogin && !$this->mStickHTTPS ) {
1075 $user->setCookies( $this->mRequest, false, $this->mRemember );
1076 } else {
1077 $user->setCookies( $this->mRequest, null, $this->mRemember );
1078 }
1079 self::clearLoginToken();
1080
1081 // Reset the throttle
1082 self::clearLoginThrottle( $this->mUsername );
1083
1084 $request = $this->getRequest();
1085 if ( $this->hasSessionCookie() || $this->mSkipCookieCheck ) {
1086 /* Replace the language object to provide user interface in
1087 * correct language immediately on this first page load.
1088 */
1089 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
1090 $userLang = Language::factory( $code );
1091 $wgLang = $userLang;
1092 RequestContext::getMain()->setLanguage( $userLang );
1093 $this->getContext()->setLanguage( $userLang );
1094 // Reset SessionID on Successful login (bug 40995)
1095 $this->renewSessionId();
1096 if ( $this->checkUserPasswordExpired( $this->getUser() ) == 'soft' ) {
1097 $this->resetLoginForm( $this->msg( 'resetpass-expired-soft' ) );
1098 } elseif ( $wgInvalidPasswordReset
1099 && !$user->isValidPassword( $this->mPassword )
1100 ) {
1101 $status = $user->checkPasswordValidity(
1102 $this->mPassword,
1103 'login'
1104 );
1105 $this->resetLoginForm(
1106 $status->getMessage( 'resetpass-validity-soft' )
1107 );
1108 } else {
1109 $this->successfulLogin();
1110 }
1111 } else {
1112 $this->cookieRedirectCheck( 'login' );
1113 }
1114 break;
1115
1116 case self::NEED_TOKEN:
1117 $error = $this->mAbortLoginErrorMsg ?: 'nocookiesforlogin';
1118 $this->mainLoginForm( $this->msg( $error )->parse() );
1119 break;
1120 case self::WRONG_TOKEN:
1121 $error = $this->mAbortLoginErrorMsg ?: 'sessionfailure';
1122 $this->mainLoginForm( $this->msg( $error )->text() );
1123 break;
1124 case self::NO_NAME:
1125 case self::ILLEGAL:
1126 $error = $this->mAbortLoginErrorMsg ?: 'noname';
1127 $this->mainLoginForm( $this->msg( $error )->text() );
1128 break;
1129 case self::WRONG_PLUGIN_PASS:
1130 $error = $this->mAbortLoginErrorMsg ?: 'wrongpassword';
1131 $this->mainLoginForm( $this->msg( $error )->text() );
1132 break;
1133 case self::NOT_EXISTS:
1134 if ( $this->getUser()->isAllowed( 'createaccount' ) ) {
1135 $error = $this->mAbortLoginErrorMsg ?: 'nosuchuser';
1136 $this->mainLoginForm( $this->msg( $error,
1137 wfEscapeWikiText( $this->mUsername ) )->parse() );
1138 } else {
1139 $error = $this->mAbortLoginErrorMsg ?: 'nosuchusershort';
1140 $this->mainLoginForm( $this->msg( $error,
1141 wfEscapeWikiText( $this->mUsername ) )->text() );
1142 }
1143 break;
1144 case self::WRONG_PASS:
1145 $error = $this->mAbortLoginErrorMsg ?: 'wrongpassword';
1146 $this->mainLoginForm( $this->msg( $error )->text() );
1147 break;
1148 case self::EMPTY_PASS:
1149 $error = $this->mAbortLoginErrorMsg ?: 'wrongpasswordempty';
1150 $this->mainLoginForm( $this->msg( $error )->text() );
1151 break;
1152 case self::RESET_PASS:
1153 $error = $this->mAbortLoginErrorMsg ?: 'resetpass_announce';
1154 $this->resetLoginForm( $this->msg( $error ) );
1155 break;
1156 case self::CREATE_BLOCKED:
1157 $this->userBlockedMessage( $this->getUser()->isBlockedFromCreateAccount() );
1158 break;
1159 case self::THROTTLED:
1160 $error = $this->mAbortLoginErrorMsg ?: 'login-throttled';
1161 $this->mainLoginForm( $this->msg( $error )
1162 ->durationParams( $this->mThrottleWait )->text()
1163 );
1164 break;
1165 case self::USER_BLOCKED:
1166 $error = $this->mAbortLoginErrorMsg ?: 'login-userblocked';
1167 $this->mainLoginForm( $this->msg( $error, $this->mUsername )->escaped() );
1168 break;
1169 case self::ABORTED:
1170 $error = $this->mAbortLoginErrorMsg ?: 'login-abort-generic';
1171 $this->mainLoginForm( $this->msg( $error,
1172 wfEscapeWikiText( $this->mUsername ) )->text() );
1173 break;
1174 case self::USER_MIGRATED:
1175 $error = $this->mAbortLoginErrorMsg ?: 'login-migrated-generic';
1176 $params = [];
1177 if ( is_array( $error ) ) {
1178 $error = array_shift( $this->mAbortLoginErrorMsg );
1179 $params = $this->mAbortLoginErrorMsg;
1180 }
1181 $this->mainLoginForm( $this->msg( $error, $params )->text() );
1182 break;
1183 default:
1184 throw new MWException( 'Unhandled case value' );
1185 }
1186
1187 LoggerFactory::getInstance( 'authmanager' )->info( 'Login attempt', [
1188 'event' => 'login',
1189 'successful' => $authRes === self::SUCCESS,
1190 'status' => LoginForm::$statusCodes[$authRes],
1191 ] );
1192 }
1193
1194 /**
1195 * Show the Special:ChangePassword form, with custom message
1196 * @param Message $msg
1197 */
1198 protected function resetLoginForm( Message $msg ) {
1199 // Allow hooks to explain this password reset in more detail
1200 Hooks::run( 'LoginPasswordResetMessage', [ &$msg, $this->mUsername ] );
1201 $reset = new SpecialChangePassword();
1202 $derivative = new DerivativeContext( $this->getContext() );
1203 $derivative->setTitle( $reset->getPageTitle() );
1204 $reset->setContext( $derivative );
1205 if ( !$this->mTempPasswordUsed ) {
1206 $reset->setOldPasswordMessage( 'oldpassword' );
1207 }
1208 $reset->setChangeMessage( $msg );
1209 $reset->execute( null );
1210 }
1211
1212 /**
1213 * @param User $u
1214 * @param bool $throttle
1215 * @param string $emailTitle Message name of email title
1216 * @param string $emailText Message name of email text
1217 * @return Status
1218 */
1219 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle',
1220 $emailText = 'passwordremindertext'
1221 ) {
1222 global $wgNewPasswordExpiry, $wgMinimalPasswordLength;
1223
1224 if ( $u->getEmail() == '' ) {
1225 return Status::newFatal( 'noemail', $u->getName() );
1226 }
1227 $ip = $this->getRequest()->getIP();
1228 if ( !$ip ) {
1229 return Status::newFatal( 'badipaddress' );
1230 }
1231
1232 $currentUser = $this->getUser();
1233 Hooks::run( 'User::mailPasswordInternal', [ &$currentUser, &$ip, &$u ] );
1234
1235 $np = PasswordFactory::generateRandomPasswordString( $wgMinimalPasswordLength );
1236 $u->setNewpassword( $np, $throttle );
1237 $u->saveSettings();
1238 $userLanguage = $u->getOption( 'language' );
1239
1240 $mainPage = Title::newMainPage();
1241 $mainPageUrl = $mainPage->getCanonicalURL();
1242
1243 $m = $this->msg( $emailText, $ip, $u->getName(), $np, '<' . $mainPageUrl . '>',
1244 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
1245 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
1246
1247 return $result;
1248 }
1249
1250 /**
1251 * Run any hooks registered for logins, then HTTP redirect to
1252 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
1253 * nice message here, but that's really not as useful as just being sent to
1254 * wherever you logged in from. It should be clear that the action was
1255 * successful, given the lack of error messages plus the appearance of your
1256 * name in the upper right.
1257 *
1258 * @private
1259 */
1260 function successfulLogin() {
1261 # Run any hooks; display injected HTML if any, else redirect
1262 $currentUser = $this->getUser();
1263 $injected_html = '';
1264 Hooks::run( 'UserLoginComplete', [ &$currentUser, &$injected_html ] );
1265
1266 if ( $injected_html !== '' ) {
1267 $this->displaySuccessfulAction( 'success', $this->msg( 'loginsuccesstitle' ),
1268 'loginsuccess', $injected_html );
1269 } else {
1270 $this->executeReturnTo( 'successredirect' );
1271 }
1272 }
1273
1274 /**
1275 * Run any hooks registered for logins, then display a message welcoming
1276 * the user.
1277 *
1278 * @private
1279 */
1280 function successfulCreation() {
1281 # Run any hooks; display injected HTML
1282 $currentUser = $this->getUser();
1283 $injected_html = '';
1284 $welcome_creation_msg = 'welcomecreation-msg';
1285
1286 Hooks::run( 'UserLoginComplete', [ &$currentUser, &$injected_html ] );
1287
1288 /**
1289 * Let any extensions change what message is shown.
1290 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
1291 * @since 1.18
1292 */
1293 Hooks::run( 'BeforeWelcomeCreation', [ &$welcome_creation_msg, &$injected_html ] );
1294
1295 $this->displaySuccessfulAction(
1296 'signup',
1297 $this->msg( 'welcomeuser', $this->getUser()->getName() ),
1298 $welcome_creation_msg, $injected_html
1299 );
1300 }
1301
1302 /**
1303 * Display a "successful action" page.
1304 *
1305 * @param string $type Condition of return to; see `executeReturnTo`
1306 * @param string|Message $title Page's title
1307 * @param string $msgname
1308 * @param string $injected_html
1309 */
1310 private function displaySuccessfulAction( $type, $title, $msgname, $injected_html ) {
1311 $out = $this->getOutput();
1312 $out->setPageTitle( $title );
1313 if ( $msgname ) {
1314 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
1315 }
1316
1317 $out->addHTML( $injected_html );
1318
1319 $this->executeReturnTo( $type );
1320 }
1321
1322 /**
1323 * Output a message that informs the user that they cannot create an account because
1324 * there is a block on them or their IP which prevents account creation. Note that
1325 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
1326 * setting on blocks (bug 13611).
1327 * @param Block $block The block causing this error
1328 * @throws ErrorPageError
1329 */
1330 function userBlockedMessage( Block $block ) {
1331 # Let's be nice about this, it's likely that this feature will be used
1332 # for blocking large numbers of innocent people, e.g. range blocks on
1333 # schools. Don't blame it on the user. There's a small chance that it
1334 # really is the user's fault, i.e. the username is blocked and they
1335 # haven't bothered to log out before trying to create an account to
1336 # evade it, but we'll leave that to their guilty conscience to figure
1337 # out.
1338 $errorParams = [
1339 $block->getTarget(),
1340 $block->mReason ? $block->mReason : $this->msg( 'blockednoreason' )->text(),
1341 $block->getByName()
1342 ];
1343
1344 if ( $block->getType() === Block::TYPE_RANGE ) {
1345 $errorMessage = 'cantcreateaccount-range-text';
1346 $errorParams[] = $this->getRequest()->getIP();
1347 } else {
1348 $errorMessage = 'cantcreateaccount-text';
1349 }
1350
1351 throw new ErrorPageError(
1352 'cantcreateaccounttitle',
1353 $errorMessage,
1354 $errorParams
1355 );
1356 }
1357
1358 /**
1359 * Add a "return to" link or redirect to it.
1360 * Extensions can use this to reuse the "return to" logic after
1361 * inject steps (such as redirection) into the login process.
1362 *
1363 * @param string $type One of the following:
1364 * - error: display a return to link ignoring $wgRedirectOnLogin
1365 * - signup: display a return to link using $wgRedirectOnLogin if needed
1366 * - success: display a return to link using $wgRedirectOnLogin if needed
1367 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1368 * @param string $returnTo
1369 * @param array|string $returnToQuery
1370 * @param bool $stickHTTPs Keep redirect link on HTTPs
1371 * @since 1.22
1372 */
1373 public function showReturnToPage(
1374 $type, $returnTo = '', $returnToQuery = '', $stickHTTPs = false
1375 ) {
1376 $this->mReturnTo = $returnTo;
1377 $this->mReturnToQuery = $returnToQuery;
1378 $this->mStickHTTPS = $stickHTTPs;
1379 $this->executeReturnTo( $type );
1380 }
1381
1382 /**
1383 * Add a "return to" link or redirect to it.
1384 *
1385 * @param string $type One of the following:
1386 * - error: display a return to link ignoring $wgRedirectOnLogin
1387 * - signup: display a return to link using $wgRedirectOnLogin if needed
1388 * - success: display a return to link using $wgRedirectOnLogin if needed
1389 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1390 */
1391 private function executeReturnTo( $type ) {
1392 global $wgRedirectOnLogin, $wgSecureLogin;
1393
1394 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
1395 $returnTo = $wgRedirectOnLogin;
1396 $returnToQuery = [];
1397 } else {
1398 $returnTo = $this->mReturnTo;
1399 $returnToQuery = wfCgiToArray( $this->mReturnToQuery );
1400 }
1401
1402 // Allow modification of redirect behavior
1403 Hooks::run( 'PostLoginRedirect', [ &$returnTo, &$returnToQuery, &$type ] );
1404
1405 $returnToTitle = Title::newFromText( $returnTo );
1406 if ( !$returnToTitle ) {
1407 $returnToTitle = Title::newMainPage();
1408 }
1409
1410 if ( $wgSecureLogin && !$this->mStickHTTPS ) {
1411 $options = [ 'http' ];
1412 $proto = PROTO_HTTP;
1413 } elseif ( $wgSecureLogin ) {
1414 $options = [ 'https' ];
1415 $proto = PROTO_HTTPS;
1416 } else {
1417 $options = [];
1418 $proto = PROTO_RELATIVE;
1419 }
1420
1421 if ( $type == 'successredirect' ) {
1422 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery, false, $proto );
1423 $this->getOutput()->redirect( $redirectUrl );
1424 } else {
1425 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery, null, $options );
1426 }
1427 }
1428
1429 /**
1430 * @param string $msg
1431 * @param string $msgtype
1432 * @throws ErrorPageError
1433 * @throws Exception
1434 * @throws FatalError
1435 * @throws MWException
1436 * @throws PermissionsError
1437 * @throws ReadOnlyError
1438 * @private
1439 */
1440 function mainLoginForm( $msg, $msgtype = 'error' ) {
1441 global $wgEnableEmail, $wgEnableUserEmail;
1442 global $wgHiddenPrefs, $wgLoginLanguageSelector;
1443 global $wgAuth, $wgEmailConfirmToEdit;
1444 global $wgSecureLogin, $wgPasswordResetRoutes;
1445 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
1446
1447 $titleObj = $this->getPageTitle();
1448 $user = $this->getUser();
1449 $out = $this->getOutput();
1450
1451 if ( $this->mType == 'signup' ) {
1452 // Block signup here if in readonly. Keeps user from
1453 // going through the process (filling out data, etc)
1454 // and being informed later.
1455 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
1456 if ( count( $permErrors ) ) {
1457 throw new PermissionsError( 'createaccount', $permErrors );
1458 } elseif ( $user->isBlockedFromCreateAccount() ) {
1459 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1460
1461 return;
1462 } elseif ( wfReadOnly() ) {
1463 throw new ReadOnlyError;
1464 }
1465 }
1466
1467 // Pre-fill username (if not creating an account, bug 44775).
1468 if ( $this->mUsername == '' && $this->mType != 'signup' ) {
1469 if ( $user->isLoggedIn() ) {
1470 $this->mUsername = $user->getName();
1471 } else {
1472 $this->mUsername = $this->getRequest()->getSession()->suggestLoginUsername();
1473 }
1474 }
1475
1476 // Generic styles and scripts for both login and signup form
1477 $out->addModuleStyles( [
1478 'mediawiki.ui',
1479 'mediawiki.ui.button',
1480 'mediawiki.ui.checkbox',
1481 'mediawiki.ui.input',
1482 'mediawiki.special.userlogin.common.styles'
1483 ] );
1484
1485 if ( $this->mType == 'signup' ) {
1486 // Additional styles and scripts for signup form
1487 $out->addModules( [
1488 'mediawiki.special.userlogin.signup.js'
1489 ] );
1490 $out->addModuleStyles( [
1491 'mediawiki.special.userlogin.signup.styles'
1492 ] );
1493
1494 $template = new UsercreateTemplate( $this->getConfig() );
1495
1496 // Must match number of benefits defined in messages
1497 $template->set( 'benefitCount', 3 );
1498
1499 $q = 'action=submitlogin&type=signup';
1500 $linkq = 'type=login';
1501 } else {
1502 // Additional styles for login form
1503 $out->addModuleStyles( [
1504 'mediawiki.special.userlogin.login.styles'
1505 ] );
1506
1507 $template = new UserloginTemplate( $this->getConfig() );
1508
1509 $q = 'action=submitlogin&type=login';
1510 $linkq = 'type=signup';
1511 }
1512
1513 if ( $this->mReturnTo !== '' ) {
1514 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
1515 if ( $this->mReturnToQuery !== '' ) {
1516 $returnto .= '&returntoquery=' .
1517 wfUrlencode( $this->mReturnToQuery );
1518 }
1519 $q .= $returnto;
1520 $linkq .= $returnto;
1521 }
1522
1523 # Don't show a "create account" link if the user can't.
1524 if ( $this->showCreateOrLoginLink( $user ) ) {
1525 # Pass any language selection on to the mode switch link
1526 if ( $wgLoginLanguageSelector && $this->mLanguage ) {
1527 $linkq .= '&uselang=' . $this->mLanguage;
1528 }
1529 // Supply URL, login template creates the button.
1530 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
1531 } else {
1532 $template->set( 'link', '' );
1533 }
1534
1535 $resetLink = $this->mType == 'signup'
1536 ? null
1537 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1538
1539 $template->set( 'header', '' );
1540 $template->set( 'formheader', '' );
1541 $template->set( 'skin', $this->getSkin() );
1542 $template->set( 'name', $this->mUsername );
1543 $template->set( 'password', $this->mPassword );
1544 $template->set( 'retype', $this->mRetype );
1545 $template->set( 'createemailset', $this->mCreateaccountMail );
1546 $template->set( 'email', $this->mEmail );
1547 $template->set( 'realname', $this->mRealName );
1548 $template->set( 'domain', $this->mDomain );
1549 $template->set( 'reason', $this->mReason );
1550
1551 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1552 $template->set( 'message', $msg );
1553 $template->set( 'messagetype', $msgtype );
1554 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1555 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1556 $template->set( 'useemail', $wgEnableEmail );
1557 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1558 $template->set( 'emailothers', $wgEnableUserEmail );
1559 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1560 $template->set( 'resetlink', $resetLink );
1561 $template->set( 'canremember', $wgExtendedLoginCookieExpiration === null ?
1562 ( $wgCookieExpiration > 0 ) :
1563 ( $wgExtendedLoginCookieExpiration > 0 ) );
1564 $template->set( 'usereason', $user->isLoggedIn() );
1565 $template->set( 'remember', $this->mRemember );
1566 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1567 $template->set( 'stickhttps', (int)$this->mStickHTTPS );
1568 $template->set( 'loggedin', $user->isLoggedIn() );
1569 $template->set( 'loggedinuser', $user->getName() );
1570
1571 if ( $this->mType == 'signup' ) {
1572 $template->set( 'token', self::getCreateaccountToken()->toString() );
1573 } else {
1574 $template->set( 'token', self::getLoginToken()->toString() );
1575 }
1576
1577 # Prepare language selection links as needed
1578 if ( $wgLoginLanguageSelector ) {
1579 $template->set( 'languages', $this->makeLanguageSelector() );
1580 if ( $this->mLanguage ) {
1581 $template->set( 'uselang', $this->mLanguage );
1582 }
1583 }
1584
1585 $template->set( 'secureLoginUrl', $this->mSecureLoginUrl );
1586 // Use signupend-https for HTTPS requests if it's not blank, signupend otherwise
1587 $usingHTTPS = $this->mRequest->getProtocol() == 'https';
1588 $signupendHTTPS = $this->msg( 'signupend-https' );
1589 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1590 $template->set( 'signupend', $signupendHTTPS->parse() );
1591 } else {
1592 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1593 }
1594
1595 // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
1596 if ( $usingHTTPS ) {
1597 $template->set( 'fromhttp', $this->mFromHTTP );
1598 }
1599
1600 // Give authentication and captcha plugins a chance to modify the form
1601 $wgAuth->modifyUITemplate( $template, $this->mType );
1602 if ( $this->mType == 'signup' ) {
1603 Hooks::run( 'UserCreateForm', [ &$template ] );
1604 } else {
1605 Hooks::run( 'UserLoginForm', [ &$template ] );
1606 }
1607
1608 $out->disallowUserJs(); // just in case...
1609 $out->addTemplate( $template );
1610 }
1611
1612 /**
1613 * Whether the login/create account form should display a link to the
1614 * other form (in addition to whatever the skin provides).
1615 *
1616 * @param User $user
1617 * @return bool
1618 */
1619 private function showCreateOrLoginLink( &$user ) {
1620 if ( $this->mType == 'signup' ) {
1621 return true;
1622 } elseif ( $user->isAllowed( 'createaccount' ) ) {
1623 return true;
1624 } else {
1625 return false;
1626 }
1627 }
1628
1629 /**
1630 * Check if a session cookie is present.
1631 *
1632 * This will not pick up a cookie set during _this_ request, but is meant
1633 * to ensure that the client is returning the cookie which was set on a
1634 * previous pass through the system.
1635 *
1636 * @private
1637 * @return bool
1638 */
1639 function hasSessionCookie() {
1640 global $wgDisableCookieCheck, $wgInitialSessionId;
1641
1642 return $wgDisableCookieCheck || (
1643 $wgInitialSessionId &&
1644 $this->getRequest()->getSession()->getId() === (string)$wgInitialSessionId
1645 );
1646 }
1647
1648 /**
1649 * Get the login token from the current session
1650 * @since 1.27 returns a MediaWiki\\Session\\Token instead of a string
1651 * @return MediaWiki\\Session\\Token
1652 */
1653 public static function getLoginToken() {
1654 global $wgRequest;
1655 return $wgRequest->getSession()->getToken( '', 'login' );
1656 }
1657
1658 /**
1659 * Formerly randomly generated a login token that would be returned by
1660 * $this->getLoginToken().
1661 *
1662 * Since 1.27, this is a no-op. The token is generated as necessary by
1663 * $this->getLoginToken().
1664 *
1665 * @deprecated since 1.27
1666 */
1667 public static function setLoginToken() {
1668 wfDeprecated( __METHOD__, '1.27' );
1669 }
1670
1671 /**
1672 * Remove any login token attached to the current session
1673 */
1674 public static function clearLoginToken() {
1675 global $wgRequest;
1676 $wgRequest->getSession()->resetToken( 'login' );
1677 }
1678
1679 /**
1680 * Get the createaccount token from the current session
1681 * @since 1.27 returns a MediaWiki\\Session\\Token instead of a string
1682 * @return MediaWiki\\Session\\Token
1683 */
1684 public static function getCreateaccountToken() {
1685 global $wgRequest;
1686 return $wgRequest->getSession()->getToken( '', 'createaccount' );
1687 }
1688
1689 /**
1690 * Formerly randomly generated a createaccount token that would be returned
1691 * by $this->getCreateaccountToken().
1692 *
1693 * Since 1.27, this is a no-op. The token is generated as necessary by
1694 * $this->getCreateaccountToken().
1695 *
1696 * @deprecated since 1.27
1697 */
1698 public static function setCreateaccountToken() {
1699 wfDeprecated( __METHOD__, '1.27' );
1700 }
1701
1702 /**
1703 * Remove any createaccount token attached to the current session
1704 */
1705 public static function clearCreateaccountToken() {
1706 global $wgRequest;
1707 $wgRequest->getSession()->resetToken( 'createaccount' );
1708 }
1709
1710 /**
1711 * Renew the user's session id, using strong entropy
1712 */
1713 private function renewSessionId() {
1714 global $wgSecureLogin, $wgCookieSecure;
1715 if ( $wgSecureLogin && !$this->mStickHTTPS ) {
1716 $wgCookieSecure = false;
1717 }
1718
1719 SessionManager::getGlobalSession()->resetId();
1720 }
1721
1722 /**
1723 * @param string $type
1724 * @private
1725 */
1726 function cookieRedirectCheck( $type ) {
1727 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
1728 $query = [ 'wpCookieCheck' => $type ];
1729 if ( $this->mReturnTo !== '' ) {
1730 $query['returnto'] = $this->mReturnTo;
1731 $query['returntoquery'] = $this->mReturnToQuery;
1732 }
1733 $check = $titleObj->getFullURL( $query );
1734
1735 $this->getOutput()->redirect( $check );
1736 }
1737
1738 /**
1739 * @param string $type
1740 * @private
1741 */
1742 function onCookieRedirectCheck( $type ) {
1743 if ( !$this->hasSessionCookie() ) {
1744 if ( $type == 'new' ) {
1745 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1746 } elseif ( $type == 'login' ) {
1747 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1748 } else {
1749 # shouldn't happen
1750 $this->mainLoginForm( $this->msg( 'error' )->text() );
1751 }
1752 } else {
1753 $this->successfulLogin();
1754 }
1755 }
1756
1757 /**
1758 * Produce a bar of links which allow the user to select another language
1759 * during login/registration but retain "returnto"
1760 *
1761 * @return string
1762 */
1763 function makeLanguageSelector() {
1764 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1765 if ( $msg->isBlank() ) {
1766 return '';
1767 }
1768 $langs = explode( "\n", $msg->text() );
1769 $links = [];
1770 foreach ( $langs as $lang ) {
1771 $lang = trim( $lang, '* ' );
1772 $parts = explode( '|', $lang );
1773 if ( count( $parts ) >= 2 ) {
1774 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1775 }
1776 }
1777
1778 return count( $links ) > 0 ? $this->msg( 'loginlanguagelabel' )->rawParams(
1779 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1780 }
1781
1782 /**
1783 * Create a language selector link for a particular language
1784 * Links back to this page preserving type and returnto
1785 *
1786 * @param string $text Link text
1787 * @param string $lang Language code
1788 * @return string
1789 */
1790 function makeLanguageSelectorLink( $text, $lang ) {
1791 if ( $this->getLanguage()->getCode() == $lang ) {
1792 // no link for currently used language
1793 return htmlspecialchars( $text );
1794 }
1795 $query = [ 'uselang' => $lang ];
1796 if ( $this->mType == 'signup' ) {
1797 $query['type'] = 'signup';
1798 }
1799 if ( $this->mReturnTo !== '' ) {
1800 $query['returnto'] = $this->mReturnTo;
1801 $query['returntoquery'] = $this->mReturnToQuery;
1802 }
1803
1804 $attr = [];
1805 $targetLanguage = Language::factory( $lang );
1806 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1807
1808 return Linker::linkKnown(
1809 $this->getPageTitle(),
1810 htmlspecialchars( $text ),
1811 $attr,
1812 $query
1813 );
1814 }
1815
1816 protected function getGroupName() {
1817 return 'login';
1818 }
1819
1820 /**
1821 * Private function to check password expiration, until AuthManager comes
1822 * along to handle that.
1823 * @param User $user
1824 * @return string|bool
1825 */
1826 private function checkUserPasswordExpired( User $user ) {
1827 global $wgPasswordExpireGrace;
1828 $dbr = wfGetDB( DB_SLAVE );
1829 $ts = $dbr->selectField( 'user', 'user_password_expires', [ 'user_id' => $user->getId() ] );
1830
1831 $expired = false;
1832 $now = wfTimestamp();
1833 $expUnix = wfTimestamp( TS_UNIX, $ts );
1834 if ( $ts !== null && $expUnix < $now ) {
1835 $expired = ( $expUnix + $wgPasswordExpireGrace < $now ) ? 'hard' : 'soft';
1836 }
1837 return $expired;
1838 }
1839
1840 protected function getSubpagesForPrefixSearch() {
1841 return [ 'signup' ];
1842 }
1843 }