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