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