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