Merge "Show warnings in HTMLForm and warnings as warnings on Login/Signup form"
[lhc/web/wiklou.git] / includes / specialpage / LoginSignupSpecialPage.php
1 <?php
2 /**
3 * Holds shared logic for login and account creation pages.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup SpecialPage
22 */
23
24 use MediaWiki\Auth\AuthenticationRequest;
25 use MediaWiki\Auth\AuthenticationResponse;
26 use MediaWiki\Auth\AuthManager;
27 use MediaWiki\Auth\Throttler;
28 use MediaWiki\Logger\LoggerFactory;
29 use MediaWiki\Session\SessionManager;
30
31 /**
32 * Holds shared logic for login and account creation pages.
33 *
34 * @ingroup SpecialPage
35 */
36 abstract class LoginSignupSpecialPage extends AuthManagerSpecialPage {
37 protected $mReturnTo;
38 protected $mPosted;
39 protected $mAction;
40 protected $mLanguage;
41 protected $mReturnToQuery;
42 protected $mToken;
43 protected $mStickHTTPS;
44 protected $mFromHTTP;
45 protected $mEntryError = '';
46 protected $mEntryErrorType = 'error';
47
48 protected $mLoaded = false;
49 protected $mLoadedRequest = false;
50 protected $mSecureLoginUrl;
51
52 /** @var string */
53 protected $securityLevel;
54
55 /** @var bool True if the user if creating an account for someone else. Flag used for internal
56 * communication, only set at the very end. */
57 protected $proxyAccountCreation;
58 /** @var User FIXME another flag for passing data. */
59 protected $targetUser;
60
61 /** @var HTMLForm */
62 protected $authForm;
63
64 /** @var FakeAuthTemplate */
65 protected $fakeTemplate;
66
67 abstract protected function isSignup();
68
69 /**
70 * @param bool $direct True if the action was successful just now; false if that happened
71 * pre-redirection (so this handler was called already)
72 * @param StatusValue|null $extraMessages
73 * @return void
74 */
75 abstract protected function successfulAction( $direct = false, $extraMessages = null );
76
77 /**
78 * Logs to the authmanager-stats channel.
79 * @param bool $success
80 * @param string|null $status Error message key
81 */
82 abstract protected function logAuthResult( $success, $status = null );
83
84 public function __construct( $name ) {
85 global $wgUseMediaWikiUIEverywhere;
86 parent::__construct( $name );
87
88 // Override UseMediaWikiEverywhere to true, to force login and create form to use mw ui
89 $wgUseMediaWikiUIEverywhere = true;
90 }
91
92 protected function setRequest( array $data, $wasPosted = null ) {
93 parent::setRequest( $data, $wasPosted );
94 $this->mLoadedRequest = false;
95 }
96
97 /**
98 * Load basic request parameters for this Special page.
99 * @param $subPage
100 */
101 private function loadRequestParameters( $subPage ) {
102 if ( $this->mLoadedRequest ) {
103 return;
104 }
105 $this->mLoadedRequest = true;
106 $request = $this->getRequest();
107
108 $this->mPosted = $request->wasPosted();
109 $this->mIsReturn = $subPage === 'return';
110 $this->mAction = $request->getVal( 'action' );
111 $this->mFromHTTP = $request->getBool( 'fromhttp', false )
112 || $request->getBool( 'wpFromhttp', false );
113 $this->mStickHTTPS = ( !$this->mFromHTTP && $request->getProtocol() === 'https' )
114 || $request->getBool( 'wpForceHttps', false );
115 $this->mLanguage = $request->getText( 'uselang' );
116 $this->mReturnTo = $request->getVal( 'returnto', '' );
117 $this->mReturnToQuery = $request->getVal( 'returntoquery', '' );
118 }
119
120 /**
121 * Load data from request.
122 * @private
123 * @param string $subPage Subpage of Special:Userlogin
124 */
125 protected function load( $subPage ) {
126 global $wgSecureLogin;
127
128 $this->loadRequestParameters( $subPage );
129 if ( $this->mLoaded ) {
130 return;
131 }
132 $this->mLoaded = true;
133 $request = $this->getRequest();
134
135 $securityLevel = $this->getRequest()->getText( 'force' );
136 if (
137 $securityLevel && AuthManager::singleton()->securitySensitiveOperationStatus(
138 $securityLevel ) === AuthManager::SEC_REAUTH
139 ) {
140 $this->securityLevel = $securityLevel;
141 }
142
143 $this->loadAuth( $subPage );
144
145 $this->mToken = $request->getVal( $this->getTokenName() );
146
147 // Show an error or warning passed on from a previous page
148 $entryError = $this->msg( $request->getVal( 'error', '' ) );
149 $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
150 // bc: provide login link as a parameter for messages where the translation
151 // was not updated
152 $loginreqlink = Linker::linkKnown(
153 $this->getPageTitle(),
154 $this->msg( 'loginreqlink' )->escaped(),
155 [],
156 [
157 'returnto' => $this->mReturnTo,
158 'returntoquery' => $this->mReturnToQuery,
159 'uselang' => $this->mLanguage,
160 'fromhttp' => $wgSecureLogin && $this->mFromHTTP ? '1' : null,
161 ]
162 );
163
164 // Only show valid error or warning messages.
165 if ( $entryError->exists()
166 && in_array( $entryError->getKey(), LoginHelper::getValidErrorMessages(), true )
167 ) {
168 $this->mEntryErrorType = 'error';
169 $this->mEntryError = $entryError->rawParams( $loginreqlink )->parse();
170
171 } elseif ( $entryWarning->exists()
172 && in_array( $entryWarning->getKey(), LoginHelper::getValidErrorMessages(), true )
173 ) {
174 $this->mEntryErrorType = 'warning';
175 $this->mEntryError = $entryWarning->rawParams( $loginreqlink )->parse();
176 }
177
178 # 1. When switching accounts, it sucks to get automatically logged out
179 # 2. Do not return to PasswordReset after a successful password change
180 # but goto Wiki start page (Main_Page) instead ( bug 33997 )
181 $returnToTitle = Title::newFromText( $this->mReturnTo );
182 if ( is_object( $returnToTitle )
183 && ( $returnToTitle->isSpecial( 'Userlogout' )
184 || $returnToTitle->isSpecial( 'PasswordReset' ) )
185 ) {
186 $this->mReturnTo = '';
187 $this->mReturnToQuery = '';
188 }
189 }
190
191 protected function getPreservedParams( $withToken = false ) {
192 global $wgSecureLogin;
193
194 $params = parent::getPreservedParams( $withToken );
195 $params += [
196 'returnto' => $this->mReturnTo ?: null,
197 'returntoquery' => $this->mReturnToQuery ?: null,
198 ];
199 if ( $wgSecureLogin && !$this->isSignup() ) {
200 $params['fromhttp'] = $this->mFromHTTP ? '1' : null;
201 }
202 return $params;
203 }
204
205 protected function beforeExecute( $subPage ) {
206 // finish initializing the class before processing the request - T135924
207 $this->loadRequestParameters( $subPage );
208 return parent::beforeExecute( $subPage );
209 }
210
211 /**
212 * @param string|null $subPage
213 */
214 public function execute( $subPage ) {
215 $authManager = AuthManager::singleton();
216 $session = SessionManager::getGlobalSession();
217
218 // Session data is used for various things in the authentication process, so we must make
219 // sure a session cookie or some equivalent mechanism is set.
220 $session->persist();
221
222 $this->load( $subPage );
223 $this->setHeaders();
224 $this->checkPermissions();
225
226 // Make sure the system configuration allows log in / sign up
227 if ( !$this->isSignup() && !$authManager->canAuthenticateNow() ) {
228 if ( !$session->canSetUser() ) {
229 throw new ErrorPageError( 'cannotloginnow-title', 'cannotloginnow-text', [
230 $session->getProvider()->describe( RequestContext::getMain()->getLanguage() )
231 ] );
232 }
233 throw new ErrorPageError( 'cannotlogin-title', 'cannotlogin-text' );
234 } elseif ( $this->isSignup() && !$authManager->canCreateAccounts() ) {
235 throw new ErrorPageError( 'cannotcreateaccount-title', 'cannotcreateaccount-text' );
236 }
237
238 /*
239 * In the case where the user is already logged in, and was redirected to
240 * the login form from a page that requires login, do not show the login
241 * page. The use case scenario for this is when a user opens a large number
242 * of tabs, is redirected to the login page on all of them, and then logs
243 * in on one, expecting all the others to work properly.
244 *
245 * However, do show the form if it was visited intentionally (no 'returnto'
246 * is present). People who often switch between several accounts have grown
247 * accustomed to this behavior.
248 *
249 * Also make an exception when force=<level> is set in the URL, which means the user must
250 * reauthenticate for security reasons.
251 */
252 if ( !$this->isSignup() && !$this->mPosted && !$this->securityLevel &&
253 ( $this->mReturnTo !== '' || $this->mReturnToQuery !== '' ) &&
254 $this->getUser()->isLoggedIn()
255 ) {
256 $this->successfulAction();
257 }
258
259 // If logging in and not on HTTPS, either redirect to it or offer a link.
260 global $wgSecureLogin;
261 if ( $this->getRequest()->getProtocol() !== 'https' ) {
262 $title = $this->getFullTitle();
263 $query = $this->getPreservedParams( false ) + [
264 'title' => null,
265 ( $this->mEntryErrorType === 'error' ? 'error'
266 : 'warning' ) => $this->mEntryError,
267 ] + $this->getRequest()->getQueryValues();
268 $url = $title->getFullURL( $query, false, PROTO_HTTPS );
269 if ( $wgSecureLogin && !$this->mFromHTTP &&
270 wfCanIPUseHTTPS( $this->getRequest()->getIP() )
271 ) {
272 // Avoid infinite redirect
273 $url = wfAppendQuery( $url, 'fromhttp=1' );
274 $this->getOutput()->redirect( $url );
275 // Since we only do this redir to change proto, always vary
276 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
277
278 return;
279 } else {
280 // A wiki without HTTPS login support should set $wgServer to
281 // http://somehost, in which case the secure URL generated
282 // above won't actually start with https://
283 if ( substr( $url, 0, 8 ) === 'https://' ) {
284 $this->mSecureLoginUrl = $url;
285 }
286 }
287 }
288
289 if ( !$this->isActionAllowed( $this->authAction ) ) {
290 // FIXME how do we explain this to the user? can we handle session loss better?
291 // messages used: authpage-cannot-login, authpage-cannot-login-continue,
292 // authpage-cannot-create, authpage-cannot-create-continue
293 $this->mainLoginForm( [], 'authpage-cannot-' . $this->authAction );
294 return;
295 }
296
297 $status = $this->trySubmit();
298
299 if ( !$status || !$status->isGood() ) {
300 $this->mainLoginForm( $this->authRequests, $status ? $status->getMessage() : '', 'error' );
301 return;
302 }
303
304 /** @var AuthenticationResponse $response */
305 $response = $status->getValue();
306
307 $returnToUrl = $this->getPageTitle( 'return' )
308 ->getFullURL( $this->getPreservedParams( true ), false, PROTO_HTTPS );
309 switch ( $response->status ) {
310 case AuthenticationResponse::PASS:
311 $this->logAuthResult( true );
312 $this->proxyAccountCreation = $this->isSignup() && !$this->getUser()->isAnon();
313 $this->targetUser = User::newFromName( $response->username );
314
315 if (
316 !$this->proxyAccountCreation
317 && $response->loginRequest
318 && $authManager->canAuthenticateNow()
319 ) {
320 // successful registration; log the user in instantly
321 $response2 = $authManager->beginAuthentication( [ $response->loginRequest ],
322 $returnToUrl );
323 if ( $response2->status !== AuthenticationResponse::PASS ) {
324 LoggerFactory::getInstance( 'login' )
325 ->error( 'Could not log in after account creation' );
326 $this->successfulAction( true, Status::newFatal( 'createacct-loginerror' ) );
327 break;
328 }
329 }
330
331 if ( !$this->proxyAccountCreation ) {
332 // Ensure that the context user is the same as the session user.
333 $this->setSessionUserForCurrentRequest();
334 }
335
336 $this->successfulAction( true );
337 break;
338 case AuthenticationResponse::FAIL:
339 // fall through
340 case AuthenticationResponse::RESTART:
341 unset( $this->authForm );
342 if ( $response->status === AuthenticationResponse::FAIL ) {
343 $action = $this->getDefaultAction( $subPage );
344 $messageType = 'error';
345 } else {
346 $action = $this->getContinueAction( $this->authAction );
347 $messageType = 'warning';
348 }
349 $this->logAuthResult( false, $response->message ? $response->message->getKey() : '-' );
350 $this->loadAuth( $subPage, $action, true );
351 $this->mainLoginForm( $this->authRequests, $response->message, $messageType );
352 break;
353 case AuthenticationResponse::REDIRECT:
354 unset( $this->authForm );
355 $this->getOutput()->redirect( $response->redirectTarget );
356 break;
357 case AuthenticationResponse::UI:
358 unset( $this->authForm );
359 $this->authAction = $this->isSignup() ? AuthManager::ACTION_CREATE_CONTINUE
360 : AuthManager::ACTION_LOGIN_CONTINUE;
361 $this->authRequests = $response->neededRequests;
362 $this->mainLoginForm( $response->neededRequests, $response->message, $response->messageType );
363 break;
364 default:
365 throw new LogicException( 'invalid AuthenticationResponse' );
366 }
367 }
368
369 /**
370 * Show the success page.
371 *
372 * @param string $type Condition of return to; see `executeReturnTo`
373 * @param string|Message $title Page's title
374 * @param string $msgname
375 * @param string $injected_html
376 * @param StatusValue|null $extraMessages
377 */
378 protected function showSuccessPage(
379 $type, $title, $msgname, $injected_html, $extraMessages
380 ) {
381 $out = $this->getOutput();
382 $out->setPageTitle( $title );
383 if ( $msgname ) {
384 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
385 }
386 if ( $extraMessages ) {
387 $extraMessages = Status::wrap( $extraMessages );
388 $out->addWikiText( $extraMessages->getWikiText() );
389 }
390
391 $out->addHTML( $injected_html );
392
393 $helper = new LoginHelper( $this->getContext() );
394 $helper->showReturnToPage( $type, $this->mReturnTo, $this->mReturnToQuery, $this->mStickHTTPS );
395 }
396
397 /**
398 * Add a "return to" link or redirect to it.
399 * Extensions can use this to reuse the "return to" logic after
400 * inject steps (such as redirection) into the login process.
401 *
402 * @param string $type One of the following:
403 * - error: display a return to link ignoring $wgRedirectOnLogin
404 * - signup: display a return to link using $wgRedirectOnLogin if needed
405 * - success: display a return to link using $wgRedirectOnLogin if needed
406 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
407 * @param string $returnTo
408 * @param array|string $returnToQuery
409 * @param bool $stickHTTPS Keep redirect link on HTTPS
410 * @since 1.22
411 */
412 public function showReturnToPage(
413 $type, $returnTo = '', $returnToQuery = '', $stickHTTPS = false
414 ) {
415 $helper = new LoginHelper( $this->getContext() );
416 $helper->showReturnToPage( $type, $returnTo, $returnToQuery, $stickHTTPS );
417 }
418
419 /**
420 * Replace some globals to make sure the fact that the user has just been logged in is
421 * reflected in the current request.
422 * @param User $user
423 */
424 protected function setSessionUserForCurrentRequest() {
425 global $wgUser, $wgLang;
426
427 $context = RequestContext::getMain();
428 $localContext = $this->getContext();
429 if ( $context !== $localContext ) {
430 // remove AuthManagerSpecialPage context hack
431 $this->setContext( $context );
432 }
433
434 $user = $context->getRequest()->getSession()->getUser();
435
436 $wgUser = $user;
437 $context->setUser( $user );
438
439 $code = $this->getRequest()->getVal( 'uselang', $user->getOption( 'language' ) );
440 $userLang = Language::factory( $code );
441 $wgLang = $userLang;
442 $context->setLanguage( $userLang );
443 }
444
445 /**
446 * @param AuthenticationRequest[] $requests A list of AuthorizationRequest objects,
447 * used to generate the form fields. An empty array means a fatal error
448 * (authentication cannot continue).
449 * @param string|Message $msg
450 * @param string $msgtype
451 * @throws ErrorPageError
452 * @throws Exception
453 * @throws FatalError
454 * @throws MWException
455 * @throws PermissionsError
456 * @throws ReadOnlyError
457 * @private
458 */
459 protected function mainLoginForm( array $requests, $msg = '', $msgtype = 'error' ) {
460 $titleObj = $this->getPageTitle();
461 $user = $this->getUser();
462 $out = $this->getOutput();
463
464 // FIXME how to handle empty $requests - restart, or no form, just an error message?
465 // no form would be better for no session type errors, restart is better when can* fails.
466 if ( !$requests ) {
467 $this->authAction = $this->getDefaultAction( $this->subPage );
468 $this->authForm = null;
469 $requests = AuthManager::singleton()->getAuthenticationRequests( $this->authAction, $user );
470 }
471
472 // Generic styles and scripts for both login and signup form
473 $out->addModuleStyles( [
474 'mediawiki.ui',
475 'mediawiki.ui.button',
476 'mediawiki.ui.checkbox',
477 'mediawiki.ui.input',
478 'mediawiki.special.userlogin.common.styles'
479 ] );
480 if ( $this->isSignup() ) {
481 // XXX hack pending RL or JS parse() support for complex content messages T27349
482 $out->addJsConfigVars( 'wgCreateacctImgcaptchaHelp',
483 $this->msg( 'createacct-imgcaptcha-help' )->parse() );
484
485 // Additional styles and scripts for signup form
486 $out->addModules( [
487 'mediawiki.special.userlogin.signup.js'
488 ] );
489 $out->addModuleStyles( [
490 'mediawiki.special.userlogin.signup.styles'
491 ] );
492 } else {
493 // Additional styles for login form
494 $out->addModuleStyles( [
495 'mediawiki.special.userlogin.login.styles'
496 ] );
497 }
498 $out->disallowUserJs(); // just in case...
499
500 $form = $this->getAuthForm( $requests, $this->authAction, $msg, $msgtype );
501 $form->prepareForm();
502 $submitStatus = Status::newGood();
503 if ( $msg && $msgtype === 'warning' ) {
504 $submitStatus->warning( $msg );
505 } elseif ( $msg && $msgtype === 'error' ) {
506 $submitStatus->fatal( $msg );
507 }
508 $formHtml = $form->getHTML( $submitStatus );
509
510 $out->addHTML( $this->getPageHtml( $formHtml ) );
511 }
512
513 /**
514 * Add page elements which are outside the form.
515 * FIXME this should probably be a template, but use a sane language (handlebars?)
516 * @param string $formHtml
517 * @return string
518 */
519 protected function getPageHtml( $formHtml ) {
520 global $wgLoginLanguageSelector;
521
522 $loginPrompt = $this->isSignup() ? '' : Html::rawElement( 'div',
523 [ 'id' => 'userloginprompt' ], $this->msg( 'loginprompt' )->parseAsBlock() );
524 $languageLinks = $wgLoginLanguageSelector ? $this->makeLanguageSelector() : '';
525 $signupStartMsg = $this->msg( 'signupstart' );
526 $signupStart = ( $this->isSignup() && !$signupStartMsg->isDisabled() )
527 ? Html::rawElement( 'div', [ 'id' => 'signupstart' ], $signupStartMsg->parseAsBlock() ) : '';
528 if ( $languageLinks ) {
529 $languageLinks = Html::rawElement( 'div', [ 'id' => 'languagelinks' ],
530 Html::rawElement( 'p', [], $languageLinks )
531 );
532 }
533
534 $benefitsContainer = '';
535 if ( $this->isSignup() && $this->showExtraInformation() ) {
536 // messages used:
537 // createacct-benefit-icon1 createacct-benefit-head1 createacct-benefit-body1
538 // createacct-benefit-icon2 createacct-benefit-head2 createacct-benefit-body2
539 // createacct-benefit-icon3 createacct-benefit-head3 createacct-benefit-body3
540 $benefitCount = 3;
541 $benefitList = '';
542 for ( $benefitIdx = 1; $benefitIdx <= $benefitCount; $benefitIdx++ ) {
543 $headUnescaped = $this->msg( "createacct-benefit-head$benefitIdx" )->text();
544 $iconClass = $this->msg( "createacct-benefit-icon$benefitIdx" )->escaped();
545 $benefitList .= Html::rawElement( 'div', [ 'class' => "mw-number-text $iconClass" ],
546 Html::rawElement( 'h3', [],
547 $this->msg( "createacct-benefit-head$benefitIdx" )->escaped()
548 )
549 . Html::rawElement( 'p', [],
550 $this->msg( "createacct-benefit-body$benefitIdx" )->params( $headUnescaped )->escaped()
551 )
552 );
553 }
554 $benefitsContainer = Html::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-container' ],
555 Html::rawElement( 'h2', [], $this->msg( 'createacct-benefit-heading' )->escaped() )
556 . Html::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-list' ],
557 $benefitList
558 )
559 );
560 }
561
562 $html = Html::rawElement( 'div', [ 'class' => 'mw-ui-container' ],
563 $loginPrompt
564 . $languageLinks
565 . $signupStart
566 . Html::rawElement( 'div', [ 'id' => 'userloginForm' ],
567 $formHtml
568 )
569 . $benefitsContainer
570 );
571
572 return $html;
573 }
574
575 /**
576 * Generates a form from the given request.
577 * @param AuthenticationRequest[] $requests
578 * @param string $action AuthManager action name
579 * @param string|Message $msg
580 * @param string $msgType
581 * @return HTMLForm
582 */
583 protected function getAuthForm( array $requests, $action, $msg = '', $msgType = 'error' ) {
584 global $wgSecureLogin, $wgLoginLanguageSelector;
585 // FIXME merge this with parent
586
587 if ( isset( $this->authForm ) ) {
588 return $this->authForm;
589 }
590
591 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
592
593 // get basic form description from the auth logic
594 $fieldInfo = AuthenticationRequest::mergeFieldInfo( $requests );
595 $fakeTemplate = $this->getFakeTemplate( $msg, $msgType );
596 $this->fakeTemplate = $fakeTemplate; // FIXME there should be a saner way to pass this to the hook
597 // this will call onAuthChangeFormFields()
598 $formDescriptor = static::fieldInfoToFormDescriptor( $requests, $fieldInfo, $this->authAction );
599 $this->postProcessFormDescriptor( $formDescriptor, $requests );
600
601 $context = $this->getContext();
602 if ( $context->getRequest() !== $this->getRequest() ) {
603 // We have overridden the request, need to make sure the form uses that too.
604 $context = new DerivativeContext( $this->getContext() );
605 $context->setRequest( $this->getRequest() );
606 }
607 $form = HTMLForm::factory( 'vform', $formDescriptor, $context );
608
609 $form->addHiddenField( 'authAction', $this->authAction );
610 if ( $wgLoginLanguageSelector ) {
611 $form->addHiddenField( 'uselang', $this->mLanguage );
612 }
613 $form->addHiddenField( 'force', $this->securityLevel );
614 $form->addHiddenField( $this->getTokenName(), $this->getToken()->toString() );
615 if ( $wgSecureLogin ) {
616 // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
617 if ( !$this->isSignup() ) {
618 $form->addHiddenField( 'wpForceHttps', (int)$this->mStickHTTPS );
619 $form->addHiddenField( 'wpFromhttp', $usingHTTPS );
620 }
621 }
622
623 // set properties of the form itself
624 $form->setAction( $this->getPageTitle()->getLocalURL( $this->getReturnToQueryStringFragment() ) );
625 $form->setName( 'userlogin' . ( $this->isSignup() ? '2' : '' ) );
626 if ( $this->isSignup() ) {
627 $form->setId( 'userlogin2' );
628 }
629
630 // warning header for non-standard workflows (e.g. security reauthentication)
631 if ( !$this->isSignup() && $this->getUser()->isLoggedIn() ) {
632 $reauthMessage = $this->securityLevel ? 'userlogin-reauth' : 'userlogin-loggedin';
633 $form->addHeaderText( Html::rawElement( 'div', [ 'class' => 'warningbox' ],
634 $this->msg( $reauthMessage )->params( $this->getUser()->getName() )->parse() ) );
635 }
636
637 $form->suppressDefaultSubmit();
638
639 $this->authForm = $form;
640
641 return $form;
642 }
643
644 /**
645 * Temporary B/C method to handle extensions using the UserLoginForm/UserCreateForm hooks.
646 * @param string|Message $msg
647 * @param string $msgType
648 * @return FakeAuthTemplate
649 */
650 protected function getFakeTemplate( $msg, $msgType ) {
651 global $wgAuth, $wgEnableEmail, $wgHiddenPrefs, $wgEmailConfirmToEdit, $wgEnableUserEmail,
652 $wgSecureLogin, $wgLoginLanguageSelector, $wgPasswordResetRoutes;
653
654 // make a best effort to get the value of fields which used to be fixed in the old login
655 // template but now might or might not exist depending on what providers are used
656 $request = $this->getRequest();
657 $data = (object) [
658 'mUsername' => $request->getText( 'wpName' ),
659 'mPassword' => $request->getText( 'wpPassword' ),
660 'mRetype' => $request->getText( 'wpRetype' ),
661 'mEmail' => $request->getText( 'wpEmail' ),
662 'mRealName' => $request->getText( 'wpRealName' ),
663 'mDomain' => $request->getText( 'wpDomain' ),
664 'mReason' => $request->getText( 'wpReason' ),
665 'mRemember' => $request->getCheck( 'wpRemember' ),
666 ];
667
668 // Preserves a bunch of logic from the old code that was rewritten in getAuthForm().
669 // There is no code reuse to make this easier to remove .
670 // If an extension tries to change any of these values, they are out of luck - we only
671 // actually use the domain/usedomain/domainnames, extraInput and extrafields keys.
672
673 $titleObj = $this->getPageTitle();
674 $user = $this->getUser();
675 $template = new FakeAuthTemplate();
676
677 // Pre-fill username (if not creating an account, bug 44775).
678 if ( $data->mUsername == '' && $this->isSignup() ) {
679 if ( $user->isLoggedIn() ) {
680 $data->mUsername = $user->getName();
681 } else {
682 $data->mUsername = $this->getRequest()->getSession()->suggestLoginUsername();
683 }
684 }
685
686 if ( $this->isSignup() ) {
687 // Must match number of benefits defined in messages
688 $template->set( 'benefitCount', 3 );
689
690 $q = 'action=submitlogin&type=signup';
691 $linkq = 'type=login';
692 } else {
693 $q = 'action=submitlogin&type=login';
694 $linkq = 'type=signup';
695 }
696
697 if ( $this->mReturnTo !== '' ) {
698 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
699 if ( $this->mReturnToQuery !== '' ) {
700 $returnto .= '&returntoquery=' .
701 wfUrlencode( $this->mReturnToQuery );
702 }
703 $q .= $returnto;
704 $linkq .= $returnto;
705 }
706
707 # Don't show a "create account" link if the user can't.
708 if ( $this->showCreateAccountLink() ) {
709 # Pass any language selection on to the mode switch link
710 if ( $wgLoginLanguageSelector && $this->mLanguage ) {
711 $linkq .= '&uselang=' . $this->mLanguage;
712 }
713 // Supply URL, login template creates the button.
714 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
715 } else {
716 $template->set( 'link', '' );
717 }
718
719 $resetLink = $this->isSignup()
720 ? null
721 : is_array( $wgPasswordResetRoutes )
722 && in_array( true, array_values( $wgPasswordResetRoutes ), true );
723
724 $template->set( 'header', '' );
725 $template->set( 'formheader', '' );
726 $template->set( 'skin', $this->getSkin() );
727
728 $template->set( 'name', $data->mUsername );
729 $template->set( 'password', $data->mPassword );
730 $template->set( 'retype', $data->mRetype );
731 $template->set( 'createemailset', false ); // no easy way to get that from AuthManager
732 $template->set( 'email', $data->mEmail );
733 $template->set( 'realname', $data->mRealName );
734 $template->set( 'domain', $data->mDomain );
735 $template->set( 'reason', $data->mReason );
736 $template->set( 'remember', $data->mRemember );
737
738 $template->set( 'action', $titleObj->getLocalURL( $q ) );
739 $template->set( 'message', $msg );
740 $template->set( 'messagetype', $msgType );
741 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
742 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs, true ) );
743 $template->set( 'useemail', $wgEnableEmail );
744 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
745 $template->set( 'emailothers', $wgEnableUserEmail );
746 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
747 $template->set( 'resetlink', $resetLink );
748 $template->set( 'canremember', $request->getSession()->getProvider()
749 ->getRememberUserDuration() !== null );
750 $template->set( 'usereason', $user->isLoggedIn() );
751 $template->set( 'cansecurelogin', ( $wgSecureLogin ) );
752 $template->set( 'stickhttps', (int)$this->mStickHTTPS );
753 $template->set( 'loggedin', $user->isLoggedIn() );
754 $template->set( 'loggedinuser', $user->getName() );
755 $template->set( 'token', $this->getToken()->toString() );
756
757 $action = $this->isSignup() ? 'signup' : 'login';
758 $wgAuth->modifyUITemplate( $template, $action );
759
760 $oldTemplate = $template;
761 $hookName = $this->isSignup() ? 'UserCreateForm' : 'UserLoginForm';
762 Hooks::run( $hookName, [ &$template ] );
763 if ( $oldTemplate !== $template ) {
764 wfDeprecated( "reference in $hookName hook", '1.27' );
765 }
766
767 return $template;
768
769 }
770
771 public function onAuthChangeFormFields(
772 array $requests, array $fieldInfo, array &$formDescriptor, $action
773 ) {
774 $coreFieldDescriptors = $this->getFieldDefinitions( $this->fakeTemplate );
775 $specialFields = array_merge( [ 'extraInput' ],
776 array_keys( $this->fakeTemplate->getExtraInputDefinitions() ) );
777
778 // keep the ordering from getCoreFieldDescriptors() where there is no explicit weight
779 foreach ( $coreFieldDescriptors as $fieldName => $coreField ) {
780 $requestField = isset( $formDescriptor[$fieldName] ) ?
781 $formDescriptor[$fieldName] : [];
782
783 // remove everything that is not in the fieldinfo, is not marked as a supplemental field
784 // to something in the fieldinfo, is not B/C for the pre-AuthManager templates,
785 // and is not an info field or a submit button
786 if (
787 !isset( $fieldInfo[$fieldName] )
788 && (
789 !isset( $coreField['baseField'] )
790 || !isset( $fieldInfo[$coreField['baseField']] )
791 )
792 && !in_array( $fieldName, $specialFields, true )
793 && (
794 !isset( $coreField['type'] )
795 || !in_array( $coreField['type'], [ 'submit', 'info' ], true )
796 )
797 ) {
798 $coreFieldDescriptors[$fieldName] = null;
799 continue;
800 }
801
802 // core message labels should always take priority
803 if (
804 isset( $coreField['label'] )
805 || isset( $coreField['label-message'] )
806 || isset( $coreField['label-raw'] )
807 ) {
808 unset( $requestField['label'], $requestField['label-message'], $coreField['label-raw'] );
809 }
810
811 $coreFieldDescriptors[$fieldName] += $requestField;
812 }
813
814 $formDescriptor = array_filter( $coreFieldDescriptors + $formDescriptor );
815 return true;
816 }
817
818 /**
819 * Show extra information such as password recovery information, link from login to signup,
820 * CTA etc? Such information should only be shown on the "landing page", ie. when the user
821 * is at the first step of the authentication process.
822 * @return bool
823 */
824 protected function showExtraInformation() {
825 return $this->authAction !== $this->getContinueAction( $this->authAction )
826 && !$this->securityLevel;
827 }
828
829 /**
830 * Create a HTMLForm descriptor for the core login fields.
831 * @param FakeAuthTemplate $template B/C data (not used but needed by getBCFieldDefinitions)
832 * @return array
833 */
834 protected function getFieldDefinitions( $template ) {
835 global $wgEmailConfirmToEdit, $wgLoginLanguageSelector;
836
837 $isLoggedIn = $this->getUser()->isLoggedIn();
838 $continuePart = $this->isContinued() ? 'continue-' : '';
839 $anotherPart = $isLoggedIn ? 'another-' : '';
840 $expiration = $this->getRequest()->getSession()->getProvider()->getRememberUserDuration();
841 $expirationDays = ceil( $expiration / ( 3600 * 24 ) );
842 $secureLoginLink = '';
843 if ( $this->mSecureLoginUrl ) {
844 $secureLoginLink = Html::element( 'a', [
845 'href' => $this->mSecureLoginUrl,
846 'class' => 'mw-ui-flush-right mw-secure',
847 ], $this->msg( 'userlogin-signwithsecure' )->text() );
848 }
849 $usernameHelpLink = '';
850 if ( !$this->msg( 'createacct-helpusername' )->isDisabled() ) {
851 $usernameHelpLink = Html::rawElement( 'span', [
852 'class' => 'mw-ui-flush-right',
853 ], $this->msg( 'createacct-helpusername' )->parse() );
854 }
855
856 if ( $this->isSignup() ) {
857 $fieldDefinitions = [
858 'statusarea' => [
859 // used by the mediawiki.special.userlogin.signup.js module for error display
860 // FIXME merge this with HTMLForm's normal status (error) area
861 'type' => 'info',
862 'raw' => true,
863 'default' => Html::element( 'div', [ 'id' => 'mw-createacct-status-area' ] ),
864 'weight' => -105,
865 ],
866 'username' => [
867 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $usernameHelpLink,
868 'id' => 'wpName2',
869 'placeholder-message' => $isLoggedIn ? 'createacct-another-username-ph'
870 : 'userlogin-yourname-ph',
871 ],
872 'mailpassword' => [
873 // create account without providing password, a temporary one will be mailed
874 'type' => 'check',
875 'label-message' => 'createaccountmail',
876 'name' => 'wpCreateaccountMail',
877 'id' => 'wpCreateaccountMail',
878 ],
879 'password' => [
880 'id' => 'wpPassword2',
881 'placeholder-message' => 'createacct-yourpassword-ph',
882 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
883 ],
884 'domain' => [],
885 'retype' => [
886 'baseField' => 'password',
887 'type' => 'password',
888 'label-message' => 'createacct-yourpasswordagain',
889 'id' => 'wpRetype',
890 'cssclass' => 'loginPassword',
891 'size' => 20,
892 'validation-callback' => function ( $value, $alldata ) {
893 if ( empty( $alldata['mailpassword'] ) && !empty( $alldata['password'] ) ) {
894 if ( !$value ) {
895 return $this->msg( 'htmlform-required' );
896 } elseif ( $value !== $alldata['password'] ) {
897 return $this->msg( 'badretype' );
898 }
899 }
900 return true;
901 },
902 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
903 'placeholder-message' => 'createacct-yourpasswordagain-ph',
904 ],
905 'email' => [
906 'type' => 'email',
907 'label-message' => $wgEmailConfirmToEdit ? 'createacct-emailrequired'
908 : 'createacct-emailoptional',
909 'id' => 'wpEmail',
910 'cssclass' => 'loginText',
911 'size' => '20',
912 // FIXME will break non-standard providers
913 'required' => $wgEmailConfirmToEdit,
914 'validation-callback' => function ( $value, $alldata ) {
915 global $wgEmailConfirmToEdit;
916
917 // AuthManager will check most of these, but that will make the auth
918 // session fail and this won't, so nicer to do it this way
919 if ( !$value && $wgEmailConfirmToEdit ) {
920 // no point in allowing registration without email when email is
921 // required to edit
922 return $this->msg( 'noemailtitle' );
923 } elseif ( !$value && !empty( $alldata['mailpassword'] ) ) {
924 // cannot send password via email when there is no email address
925 return $this->msg( 'noemailcreate' );
926 } elseif ( $value && !Sanitizer::validateEmail( $value ) ) {
927 return $this->msg( 'invalidemailaddress' );
928 }
929 return true;
930 },
931 'placeholder-message' => 'createacct-' . $anotherPart . 'email-ph',
932 ],
933 'realname' => [
934 'type' => 'text',
935 'help-message' => $isLoggedIn ? 'createacct-another-realname-tip'
936 : 'prefs-help-realname',
937 'label-message' => 'createacct-realname',
938 'cssclass' => 'loginText',
939 'size' => 20,
940 'id' => 'wpRealName',
941 ],
942 'reason' => [
943 // comment for the user creation log
944 'type' => 'text',
945 'label-message' => 'createacct-reason',
946 'cssclass' => 'loginText',
947 'id' => 'wpReason',
948 'size' => '20',
949 'placeholder-message' => 'createacct-reason-ph',
950 ],
951 'extrainput' => [], // placeholder for fields coming from the template
952 'createaccount' => [
953 // submit button
954 'type' => 'submit',
955 'default' => $this->msg( 'createacct-' . $anotherPart . $continuePart .
956 'submit' )->text(),
957 'name' => 'wpCreateaccount',
958 'id' => 'wpCreateaccount',
959 'weight' => 100,
960 ],
961 ];
962 } else {
963 $fieldDefinitions = [
964 'username' => [
965 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $secureLoginLink,
966 'id' => 'wpName1',
967 'placeholder-message' => 'userlogin-yourname-ph',
968 ],
969 'password' => [
970 'id' => 'wpPassword1',
971 'placeholder-message' => 'userlogin-yourpassword-ph',
972 ],
973 'domain' => [],
974 'extrainput' => [],
975 'rememberMe' => [
976 // option for saving the user token to a cookie
977 'type' => 'check',
978 'name' => 'wpRemember',
979 'label-message' => $this->msg( 'userlogin-remembermypassword' )
980 ->numParams( $expirationDays ),
981 'id' => 'wpRemember',
982 ],
983 'loginattempt' => [
984 // submit button
985 'type' => 'submit',
986 'default' => $this->msg( 'pt-login-' . $continuePart . 'button' )->text(),
987 'id' => 'wpLoginAttempt',
988 'weight' => 100,
989 ],
990 'linkcontainer' => [
991 // help link
992 'type' => 'info',
993 'cssclass' => 'mw-form-related-link-container mw-userlogin-help',
994 // 'id' => 'mw-userlogin-help', // FIXME HTMLInfoField ignores this
995 'raw' => true,
996 'default' => Html::element( 'a', [
997 'href' => Skin::makeInternalOrExternalUrl( wfMessage( 'helplogin-url' )
998 ->inContentLanguage()
999 ->text() ),
1000 ], $this->msg( 'userlogin-helplink2' )->text() ),
1001 'weight' => 200,
1002 ],
1003 // button for ResetPasswordSecondaryAuthenticationProvider
1004 'skipReset' => [
1005 'weight' => 110,
1006 'flags' => [],
1007 ],
1008 ];
1009 }
1010
1011 $fieldDefinitions['username'] += [
1012 'type' => 'text',
1013 'name' => 'wpName',
1014 'cssclass' => 'loginText',
1015 'size' => 20,
1016 // 'required' => true,
1017 ];
1018 $fieldDefinitions['password'] += [
1019 'type' => 'password',
1020 // 'label-message' => 'userlogin-yourpassword', // would override the changepassword label
1021 'name' => 'wpPassword',
1022 'cssclass' => 'loginPassword',
1023 'size' => 20,
1024 // 'required' => true,
1025 ];
1026
1027 if ( $template->get( 'header' ) || $template->get( 'formheader' ) ) {
1028 // B/C for old extensions that haven't been converted to AuthManager (or have been
1029 // but somebody is using the old version) and still use templates via the
1030 // UserCreateForm/UserLoginForm hook.
1031 // 'header' used by ConfirmEdit, CondfirmAccount, Persona, WikimediaIncubator, SemanticSignup
1032 // 'formheader' used by MobileFrontend
1033 $fieldDefinitions['header'] = [
1034 'type' => 'info',
1035 'raw' => true,
1036 'default' => $template->get( 'header' ) ?: $template->get( 'formheader' ),
1037 'weight' => - 110,
1038 ];
1039 }
1040 if ( $this->mEntryError ) {
1041 $fieldDefinitions['entryError'] = [
1042 'type' => 'info',
1043 'default' => Html::rawElement( 'div', [ 'class' => $this->mEntryErrorType . 'box', ],
1044 $this->mEntryError ),
1045 'raw' => true,
1046 'rawrow' => true,
1047 'weight' => -100,
1048 ];
1049 }
1050 if ( !$this->showExtraInformation() ) {
1051 unset( $fieldDefinitions['linkcontainer'], $fieldDefinitions['signupend'] );
1052 }
1053 if ( $this->isSignup() && $this->showExtraInformation() ) {
1054 // blank signup footer for site customization
1055 // uses signupend-https for HTTPS requests if it's not blank, signupend otherwise
1056 $signupendMsg = $this->msg( 'signupend' );
1057 $signupendHttpsMsg = $this->msg( 'signupend-https' );
1058 if ( !$signupendMsg->isDisabled() ) {
1059 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
1060 $signupendText = ( $usingHTTPS && !$signupendHttpsMsg->isBlank() )
1061 ? $signupendHttpsMsg ->parse() : $signupendMsg->parse();
1062 $fieldDefinitions['signupend'] = [
1063 'type' => 'info',
1064 'raw' => true,
1065 'default' => Html::rawElement( 'div', [ 'id' => 'signupend' ], $signupendText ),
1066 'weight' => 225,
1067 ];
1068 }
1069 }
1070 if ( !$this->isSignup() && $this->showExtraInformation() ) {
1071 $passwordReset = new PasswordReset( $this->getConfig(), AuthManager::singleton() );
1072 if ( $passwordReset->isAllowed( $this->getUser() ) ) {
1073 $fieldDefinitions['passwordReset'] = [
1074 'type' => 'info',
1075 'raw' => true,
1076 'cssclass' => 'mw-form-related-link-container',
1077 'default' => Linker::link(
1078 SpecialPage::getTitleFor( 'PasswordReset' ),
1079 $this->msg( 'userlogin-resetpassword-link' )->escaped()
1080 ),
1081 'weight' => 230,
1082 ];
1083 }
1084
1085 // Don't show a "create account" link if the user can't.
1086 if ( $this->showCreateAccountLink() ) {
1087 // link to the other action
1088 $linkTitle = $this->getTitleFor( $this->isSignup() ? 'Userlogin' :'CreateAccount' );
1089 $linkq = $this->getReturnToQueryStringFragment();
1090 // Pass any language selection on to the mode switch link
1091 if ( $wgLoginLanguageSelector && $this->mLanguage ) {
1092 $linkq .= '&uselang=' . $this->mLanguage;
1093 }
1094 $loggedIn = $this->getUser()->isLoggedIn();
1095
1096 $fieldDefinitions['createOrLogin'] = [
1097 'type' => 'info',
1098 'raw' => true,
1099 'linkQuery' => $linkq,
1100 'default' => function ( $params ) use ( $loggedIn, $linkTitle ) {
1101 return Html::rawElement( 'div',
1102 [ 'id' => 'mw-createaccount' . ( !$loggedIn ? '-cta' : '' ),
1103 'class' => ( $loggedIn ? 'mw-form-related-link-container' : 'mw-ui-vform-field' ) ],
1104 ( $loggedIn ? '' : $this->msg( 'userlogin-noaccount' )->escaped() )
1105 . Html::element( 'a',
1106 [
1107 'id' => 'mw-createaccount-join' . ( $loggedIn ? '-loggedin' : '' ),
1108 'href' => $linkTitle->getLocalURL( $params['linkQuery'] ),
1109 'class' => ( $loggedIn ? '' : 'mw-ui-button' ),
1110 'tabindex' => 100,
1111 ],
1112 $this->msg(
1113 $loggedIn ? 'userlogin-createanother' : 'userlogin-joinproject'
1114 )->escaped()
1115 )
1116 );
1117 },
1118 'weight' => 235,
1119 ];
1120 }
1121 }
1122
1123 $fieldDefinitions = $this->getBCFieldDefinitions( $fieldDefinitions, $template );
1124 $fieldDefinitions = array_filter( $fieldDefinitions );
1125
1126 return $fieldDefinitions;
1127 }
1128
1129 /**
1130 * Adds fields provided via the deprecated UserLoginForm / UserCreateForm hooks
1131 * @param $fieldDefinitions array
1132 * @param FakeAuthTemplate $template
1133 * @return array
1134 */
1135 protected function getBCFieldDefinitions( $fieldDefinitions, $template ) {
1136 if ( $template->get( 'usedomain', false ) ) {
1137 // TODO probably should be translated to the new domain notation in AuthManager
1138 $fieldDefinitions['domain'] = [
1139 'type' => 'select',
1140 'label-message' => 'yourdomainname',
1141 'options' => array_combine( $template->get( 'domainnames', [] ),
1142 $template->get( 'domainnames', [] ) ),
1143 'default' => $template->get( 'domain', '' ),
1144 'name' => 'wpDomain',
1145 // FIXME id => 'mw-user-domain-section' on the parent div
1146 ];
1147 }
1148
1149 // poor man's associative array_splice
1150 $extraInputPos = array_search( 'extrainput', array_keys( $fieldDefinitions ), true );
1151 $fieldDefinitions = array_slice( $fieldDefinitions, 0, $extraInputPos, true )
1152 + $template->getExtraInputDefinitions()
1153 + array_slice( $fieldDefinitions, $extraInputPos + 1, null, true );
1154
1155 return $fieldDefinitions;
1156 }
1157
1158 /**
1159 * Check if a session cookie is present.
1160 *
1161 * This will not pick up a cookie set during _this_ request, but is meant
1162 * to ensure that the client is returning the cookie which was set on a
1163 * previous pass through the system.
1164 *
1165 * @return bool
1166 */
1167 protected function hasSessionCookie() {
1168 global $wgDisableCookieCheck, $wgInitialSessionId;
1169
1170 return $wgDisableCookieCheck || (
1171 $wgInitialSessionId &&
1172 $this->getRequest()->getSession()->getId() === (string)$wgInitialSessionId
1173 );
1174 }
1175
1176 /**
1177 * Returns a string that can be appended to the URL (without encoding) to preserve the
1178 * return target. Does not include leading '?'/'&'.
1179 */
1180 protected function getReturnToQueryStringFragment() {
1181 $returnto = '';
1182 if ( $this->mReturnTo !== '' ) {
1183 $returnto = 'returnto=' . wfUrlencode( $this->mReturnTo );
1184 if ( $this->mReturnToQuery !== '' ) {
1185 $returnto .= '&returntoquery=' . wfUrlencode( $this->mReturnToQuery );
1186 }
1187 }
1188 return $returnto;
1189 }
1190
1191 /**
1192 * Whether the login/create account form should display a link to the
1193 * other form (in addition to whatever the skin provides).
1194 * @return bool
1195 */
1196 private function showCreateAccountLink() {
1197 if ( $this->isSignup() ) {
1198 return true;
1199 } elseif ( $this->getUser()->isAllowed( 'createaccount' ) ) {
1200 return true;
1201 } else {
1202 return false;
1203 }
1204 }
1205
1206 protected function getTokenName() {
1207 return $this->isSignup() ? 'wpCreateaccountToken' : 'wpLoginToken';
1208 }
1209
1210 /**
1211 * Produce a bar of links which allow the user to select another language
1212 * during login/registration but retain "returnto"
1213 *
1214 * @return string
1215 */
1216 protected function makeLanguageSelector() {
1217 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1218 if ( $msg->isBlank() ) {
1219 return '';
1220 }
1221 $langs = explode( "\n", $msg->text() );
1222 $links = [];
1223 foreach ( $langs as $lang ) {
1224 $lang = trim( $lang, '* ' );
1225 $parts = explode( '|', $lang );
1226 if ( count( $parts ) >= 2 ) {
1227 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1228 }
1229 }
1230
1231 return count( $links ) > 0 ? $this->msg( 'loginlanguagelabel' )->rawParams(
1232 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1233 }
1234
1235 /**
1236 * Create a language selector link for a particular language
1237 * Links back to this page preserving type and returnto
1238 *
1239 * @param string $text Link text
1240 * @param string $lang Language code
1241 * @return string
1242 */
1243 protected function makeLanguageSelectorLink( $text, $lang ) {
1244 if ( $this->getLanguage()->getCode() == $lang ) {
1245 // no link for currently used language
1246 return htmlspecialchars( $text );
1247 }
1248 $query = [ 'uselang' => $lang ];
1249 if ( $this->mReturnTo !== '' ) {
1250 $query['returnto'] = $this->mReturnTo;
1251 $query['returntoquery'] = $this->mReturnToQuery;
1252 }
1253
1254 $attr = [];
1255 $targetLanguage = Language::factory( $lang );
1256 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1257
1258 return Linker::linkKnown(
1259 $this->getPageTitle(),
1260 htmlspecialchars( $text ),
1261 $attr,
1262 $query
1263 );
1264 }
1265
1266 protected function getGroupName() {
1267 return 'login';
1268 }
1269
1270 /**
1271 * @param array $formDescriptor
1272 */
1273 protected function postProcessFormDescriptor( &$formDescriptor, $requests ) {
1274 // Pre-fill username (if not creating an account, T46775).
1275 if (
1276 isset( $formDescriptor['username'] ) &&
1277 !isset( $formDescriptor['username']['default'] ) &&
1278 !$this->isSignup()
1279 ) {
1280 $user = $this->getUser();
1281 if ( $user->isLoggedIn() ) {
1282 $formDescriptor['username']['default'] = $user->getName();
1283 } else {
1284 $formDescriptor['username']['default'] =
1285 $this->getRequest()->getSession()->suggestLoginUsername();
1286 }
1287 }
1288
1289 // don't show a submit button if there is nothing to submit (i.e. the only form content
1290 // is other submit buttons, for redirect flows)
1291 if ( !$this->needsSubmitButton( $requests ) ) {
1292 unset( $formDescriptor['createaccount'], $formDescriptor['loginattempt'] );
1293 }
1294
1295 if ( !$this->isSignup() ) {
1296 // FIXME HACK don't focus on non-empty field
1297 // maybe there should be an autofocus-if similar to hide-if?
1298 if (
1299 isset( $formDescriptor['username'] )
1300 && empty( $formDescriptor['username']['default'] )
1301 && !$this->getRequest()->getCheck( 'wpName' )
1302 ) {
1303 $formDescriptor['username']['autofocus'] = true;
1304 } elseif ( isset( $formDescriptor['password'] ) ) {
1305 $formDescriptor['password']['autofocus'] = true;
1306 }
1307 }
1308
1309 $this->addTabIndex( $formDescriptor );
1310 }
1311 }
1312
1313 /**
1314 * B/C class to try handling login/signup template modifications even though login/signup does not
1315 * actually happen through a template anymore. Just collects extra field definitions and allows
1316 * some other class to do decide what to do with threm..
1317 * TODO find the right place for adding extra fields and kill this
1318 */
1319 class FakeAuthTemplate extends BaseTemplate {
1320 public function execute() {
1321 throw new LogicException( 'not used' );
1322 }
1323
1324 /**
1325 * Extensions (AntiSpoof and TitleBlacklist) call this in response to
1326 * UserCreateForm hook to add checkboxes to the create account form.
1327 */
1328 public function addInputItem( $name, $value, $type, $msg, $helptext = false ) {
1329 // use the same indexes as UserCreateForm just in case someone adds an item manually
1330 $this->data['extrainput'][] = [
1331 'name' => $name,
1332 'value' => $value,
1333 'type' => $type,
1334 'msg' => $msg,
1335 'helptext' => $helptext,
1336 ];
1337 }
1338
1339 /**
1340 * Turns addInputItem-style field definitions into HTMLForm field definitions.
1341 * @return array
1342 */
1343 public function getExtraInputDefinitions() {
1344 $definitions = [];
1345
1346 foreach ( $this->get( 'extrainput', [] ) as $field ) {
1347 $definition = [
1348 'type' => $field['type'] === 'checkbox' ? 'check' : $field['type'],
1349 'name' => $field['name'],
1350 'value' => $field['value'],
1351 'id' => $field['name'],
1352 ];
1353 if ( $field['msg'] ) {
1354 $definition['label-message'] = $this->getMsg( $field['msg'] );
1355 }
1356 if ( $field['helptext'] ) {
1357 $definition['help'] = $this->msgWiki( $field['helptext'] );
1358 }
1359
1360 // the array key doesn't matter much when name is defined explicitly but
1361 // let's try and follow HTMLForm conventions
1362 $name = preg_replace( '/^wp(?=[A-Z])/', '', $field['name'] );
1363 $definitions[$name] = $definition;
1364 }
1365
1366 if ( $this->haveData( 'extrafields' ) ) {
1367 $definitions['extrafields'] = [
1368 'type' => 'info',
1369 'raw' => true,
1370 'default' => $this->get( 'extrafields' ),
1371 ];
1372 }
1373
1374 return $definitions;
1375 }
1376 }
1377
1378 /**
1379 * LoginForm as a special page has been replaced by SpecialUserLogin and SpecialCreateAccount,
1380 * but some extensions called its public methods directly, so the class is retained as a
1381 * B/C wrapper. Anything that used it before should use AuthManager instead.
1382 */
1383 class LoginForm extends SpecialPage {
1384 const SUCCESS = 0;
1385 const NO_NAME = 1;
1386 const ILLEGAL = 2;
1387 const WRONG_PLUGIN_PASS = 3;
1388 const NOT_EXISTS = 4;
1389 const WRONG_PASS = 5;
1390 const EMPTY_PASS = 6;
1391 const RESET_PASS = 7;
1392 const ABORTED = 8;
1393 const CREATE_BLOCKED = 9;
1394 const THROTTLED = 10;
1395 const USER_BLOCKED = 11;
1396 const NEED_TOKEN = 12;
1397 const WRONG_TOKEN = 13;
1398 const USER_MIGRATED = 14;
1399
1400 public static $statusCodes = [
1401 self::SUCCESS => 'success',
1402 self::NO_NAME => 'no_name',
1403 self::ILLEGAL => 'illegal',
1404 self::WRONG_PLUGIN_PASS => 'wrong_plugin_pass',
1405 self::NOT_EXISTS => 'not_exists',
1406 self::WRONG_PASS => 'wrong_pass',
1407 self::EMPTY_PASS => 'empty_pass',
1408 self::RESET_PASS => 'reset_pass',
1409 self::ABORTED => 'aborted',
1410 self::CREATE_BLOCKED => 'create_blocked',
1411 self::THROTTLED => 'throttled',
1412 self::USER_BLOCKED => 'user_blocked',
1413 self::NEED_TOKEN => 'need_token',
1414 self::WRONG_TOKEN => 'wrong_token',
1415 self::USER_MIGRATED => 'user_migrated',
1416 ];
1417
1418 /**
1419 * @param WebRequest $request
1420 */
1421 public function __construct( $request = null ) {
1422 wfDeprecated( 'LoginForm', '1.27' );
1423 parent::__construct();
1424 }
1425
1426 /**
1427 * @deprecated since 1.27 - call LoginHelper::getValidErrorMessages instead.
1428 */
1429 public static function getValidErrorMessages() {
1430 return LoginHelper::getValidErrorMessages();
1431 }
1432
1433 /**
1434 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1435 */
1436 public static function incrementLoginThrottle( $username ) {
1437 wfDeprecated( __METHOD__, "1.27" );
1438 global $wgRequest;
1439 $username = User::getCanonicalName( $username, 'usable' ) ?: $username;
1440 $throttler = new Throttler();
1441 return $throttler->increase( $username, $wgRequest->getIP(), __METHOD__ );
1442 }
1443
1444 /**
1445 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1446 */
1447 public static function incLoginThrottle( $username ) {
1448 wfDeprecated( __METHOD__, "1.27" );
1449 $res = self::incrementLoginThrottle( $username );
1450 return is_array( $res ) ? true : 0;
1451 }
1452
1453 /**
1454 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1455 */
1456 public static function clearLoginThrottle( $username ) {
1457 wfDeprecated( __METHOD__, "1.27" );
1458 global $wgRequest;
1459 $username = User::getCanonicalName( $username, 'usable' ) ?: $username;
1460 $throttler = new Throttler();
1461 return $throttler->clear( $username, $wgRequest->getIP() );
1462 }
1463
1464 /**
1465 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1466 */
1467 public static function getLoginToken() {
1468 wfDeprecated( __METHOD__, '1.27' );
1469 global $wgRequest;
1470 return $wgRequest->getSession()->getToken( '', 'login' )->toString();
1471 }
1472
1473 /**
1474 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1475 */
1476 public static function setLoginToken() {
1477 wfDeprecated( __METHOD__, '1.27' );
1478 }
1479
1480 /**
1481 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1482 */
1483 public static function clearLoginToken() {
1484 wfDeprecated( __METHOD__, '1.27' );
1485 global $wgRequest;
1486 $wgRequest->getSession()->resetToken( 'login' );
1487 }
1488
1489 /**
1490 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1491 */
1492 public static function getCreateaccountToken() {
1493 wfDeprecated( __METHOD__, '1.27' );
1494 global $wgRequest;
1495 return $wgRequest->getSession()->getToken( '', 'createaccount' )->toString();
1496 }
1497
1498 /**
1499 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1500 */
1501 public static function setCreateaccountToken() {
1502 wfDeprecated( __METHOD__, '1.27' );
1503 }
1504
1505 /**
1506 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1507 */
1508 public static function clearCreateaccountToken() {
1509 wfDeprecated( __METHOD__, '1.27' );
1510 global $wgRequest;
1511 $wgRequest->getSession()->resetToken( 'createaccount' );
1512 }
1513 }