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