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