resourceloader: Remove comment about XmlJsCode wrapper
[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\Logger\LoggerFactory;
28 use MediaWiki\MediaWikiServices;
29 use MediaWiki\Session\SessionManager;
30 use Wikimedia\ScopedCallback;
31
32 /**
33 * Holds shared logic for login and account creation pages.
34 *
35 * @ingroup SpecialPage
36 */
37 abstract class LoginSignupSpecialPage extends AuthManagerSpecialPage {
38 protected $mReturnTo;
39 protected $mPosted;
40 protected $mAction;
41 protected $mLanguage;
42 protected $mReturnToQuery;
43 protected $mToken;
44 protected $mStickHTTPS;
45 protected $mFromHTTP;
46 protected $mEntryError = '';
47 protected $mEntryErrorType = 'error';
48
49 protected $mLoaded = false;
50 protected $mLoadedRequest = false;
51 protected $mSecureLoginUrl;
52
53 /** @var string */
54 protected $securityLevel;
55
56 /** @var bool True if the user if creating an account for someone else. Flag used for internal
57 * communication, only set at the very end.
58 */
59 protected $proxyAccountCreation;
60 /** @var User FIXME another flag for passing data. */
61 protected $targetUser;
62
63 /** @var HTMLForm */
64 protected $authForm;
65
66 abstract protected function isSignup();
67
68 /**
69 * @param bool $direct True if the action was successful just now; false if that happened
70 * pre-redirection (so this handler was called already)
71 * @param StatusValue|null $extraMessages
72 * @return void
73 */
74 abstract protected function successfulAction( $direct = false, $extraMessages = null );
75
76 /**
77 * Logs to the authmanager-stats channel.
78 * @param bool $success
79 * @param string|null $status Error message key
80 */
81 abstract protected function logAuthResult( $success, $status = null );
82
83 public function __construct( $name ) {
84 global $wgUseMediaWikiUIEverywhere;
85 parent::__construct( $name );
86
87 // Override UseMediaWikiEverywhere to true, to force login and create form to use mw ui
88 $wgUseMediaWikiUIEverywhere = true;
89 }
90
91 protected function setRequest( array $data, $wasPosted = null ) {
92 parent::setRequest( $data, $wasPosted );
93 $this->mLoadedRequest = false;
94 }
95
96 /**
97 * Load basic request parameters for this Special page.
98 * @param string $subPage
99 */
100 private function loadRequestParameters( $subPage ) {
101 if ( $this->mLoadedRequest ) {
102 return;
103 }
104 $this->mLoadedRequest = true;
105 $request = $this->getRequest();
106
107 $this->mPosted = $request->wasPosted();
108 $this->mIsReturn = $subPage === 'return';
109 $this->mAction = $request->getVal( 'action' );
110 $this->mFromHTTP = $request->getBool( 'fromhttp', false )
111 || $request->getBool( 'wpFromhttp', false );
112 $this->mStickHTTPS = ( !$this->mFromHTTP && $request->getProtocol() === 'https' )
113 || $request->getBool( 'wpForceHttps', false );
114 $this->mLanguage = $request->getText( 'uselang' );
115 $this->mReturnTo = $request->getVal( 'returnto', '' );
116 $this->mReturnToQuery = $request->getVal( 'returntoquery', '' );
117 }
118
119 /**
120 * Load data from request.
121 * @private
122 * @param string $subPage Subpage of Special:Userlogin
123 */
124 protected function load( $subPage ) {
125 global $wgSecureLogin;
126
127 $this->loadRequestParameters( $subPage );
128 if ( $this->mLoaded ) {
129 return;
130 }
131 $this->mLoaded = true;
132 $request = $this->getRequest();
133
134 $securityLevel = $this->getRequest()->getText( 'force' );
135 if (
136 $securityLevel && AuthManager::singleton()->securitySensitiveOperationStatus(
137 $securityLevel ) === AuthManager::SEC_REAUTH
138 ) {
139 $this->securityLevel = $securityLevel;
140 }
141
142 $this->loadAuth( $subPage );
143
144 $this->mToken = $request->getVal( $this->getTokenName() );
145
146 // Show an error or warning passed on from a previous page
147 $entryError = $this->msg( $request->getVal( 'error', '' ) );
148 $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
149 // bc: provide login link as a parameter for messages where the translation
150 // was not updated
151 $loginreqlink = $this->getLinkRenderer()->makeKnownLink(
152 $this->getPageTitle(),
153 $this->msg( 'loginreqlink' )->text(),
154 [],
155 [
156 'returnto' => $this->mReturnTo,
157 'returntoquery' => $this->mReturnToQuery,
158 'uselang' => $this->mLanguage ?: null,
159 'fromhttp' => $wgSecureLogin && $this->mFromHTTP ? '1' : null,
160 ]
161 );
162
163 // Only show valid error or warning messages.
164 if ( $entryError->exists()
165 && in_array( $entryError->getKey(), LoginHelper::getValidErrorMessages(), true )
166 ) {
167 $this->mEntryErrorType = 'error';
168 $this->mEntryError = $entryError->rawParams( $loginreqlink )->parse();
169
170 } elseif ( $entryWarning->exists()
171 && in_array( $entryWarning->getKey(), LoginHelper::getValidErrorMessages(), true )
172 ) {
173 $this->mEntryErrorType = 'warning';
174 $this->mEntryError = $entryWarning->rawParams( $loginreqlink )->parse();
175 }
176
177 # 1. When switching accounts, it sucks to get automatically logged out
178 # 2. Do not return to PasswordReset after a successful password change
179 # but goto Wiki start page (Main_Page) instead ( T35997 )
180 $returnToTitle = Title::newFromText( $this->mReturnTo );
181 if ( is_object( $returnToTitle )
182 && ( $returnToTitle->isSpecial( 'Userlogout' )
183 || $returnToTitle->isSpecial( 'PasswordReset' ) )
184 ) {
185 $this->mReturnTo = '';
186 $this->mReturnToQuery = '';
187 }
188 }
189
190 protected function getPreservedParams( $withToken = false ) {
191 global $wgSecureLogin;
192
193 $params = parent::getPreservedParams( $withToken );
194 $params += [
195 'returnto' => $this->mReturnTo ?: null,
196 'returntoquery' => $this->mReturnToQuery ?: null,
197 ];
198 if ( $wgSecureLogin && !$this->isSignup() ) {
199 $params['fromhttp'] = $this->mFromHTTP ? '1' : null;
200 }
201 return $params;
202 }
203
204 protected function beforeExecute( $subPage ) {
205 // finish initializing the class before processing the request - T135924
206 $this->loadRequestParameters( $subPage );
207 return parent::beforeExecute( $subPage );
208 }
209
210 /**
211 * @param string|null $subPage
212 * @suppress PhanTypeObjectUnsetDeclaredProperty
213 */
214 public function execute( $subPage ) {
215 if ( $this->mPosted ) {
216 $time = microtime( true );
217 $profilingScope = new ScopedCallback( function () use ( $time ) {
218 $time = microtime( true ) - $time;
219 $statsd = MediaWikiServices::getInstance()->getStatsdDataFactory();
220 $statsd->timing( "timing.login.ui.{$this->authAction}", $time * 1000 );
221 } );
222 }
223
224 $authManager = AuthManager::singleton();
225 $session = SessionManager::getGlobalSession();
226
227 // Session data is used for various things in the authentication process, so we must make
228 // sure a session cookie or some equivalent mechanism is set.
229 $session->persist();
230
231 $this->load( $subPage );
232 $this->setHeaders();
233 $this->checkPermissions();
234
235 // Make sure the system configuration allows log in / sign up
236 if ( !$this->isSignup() && !$authManager->canAuthenticateNow() ) {
237 if ( !$session->canSetUser() ) {
238 throw new ErrorPageError( 'cannotloginnow-title', 'cannotloginnow-text', [
239 $session->getProvider()->describe( RequestContext::getMain()->getLanguage() )
240 ] );
241 }
242 throw new ErrorPageError( 'cannotlogin-title', 'cannotlogin-text' );
243 } elseif ( $this->isSignup() && !$authManager->canCreateAccounts() ) {
244 throw new ErrorPageError( 'cannotcreateaccount-title', 'cannotcreateaccount-text' );
245 }
246
247 /*
248 * In the case where the user is already logged in, and was redirected to
249 * the login form from a page that requires login, do not show the login
250 * page. The use case scenario for this is when a user opens a large number
251 * of tabs, is redirected to the login page on all of them, and then logs
252 * in on one, expecting all the others to work properly.
253 *
254 * However, do show the form if it was visited intentionally (no 'returnto'
255 * is present). People who often switch between several accounts have grown
256 * accustomed to this behavior.
257 *
258 * Also make an exception when force=<level> is set in the URL, which means the user must
259 * reauthenticate for security reasons.
260 */
261 if ( !$this->isSignup() && !$this->mPosted && !$this->securityLevel &&
262 ( $this->mReturnTo !== '' || $this->mReturnToQuery !== '' ) &&
263 $this->getUser()->isLoggedIn()
264 ) {
265 $this->successfulAction();
266 return;
267 }
268
269 // If logging in and not on HTTPS, either redirect to it or offer a link.
270 global $wgSecureLogin;
271 if ( $this->getRequest()->getProtocol() !== 'https' ) {
272 $title = $this->getFullTitle();
273 $query = $this->getPreservedParams( false ) + [
274 'title' => null,
275 ( $this->mEntryErrorType === 'error' ? 'error'
276 : 'warning' ) => $this->mEntryError,
277 ] + $this->getRequest()->getQueryValues();
278 $url = $title->getFullURL( $query, false, PROTO_HTTPS );
279 if ( $wgSecureLogin && !$this->mFromHTTP &&
280 wfCanIPUseHTTPS( $this->getRequest()->getIP() )
281 ) {
282 // Avoid infinite redirect
283 $url = wfAppendQuery( $url, 'fromhttp=1' );
284 $this->getOutput()->redirect( $url );
285 // Since we only do this redir to change proto, always vary
286 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
287
288 return;
289 } else {
290 // A wiki without HTTPS login support should set $wgServer to
291 // http://somehost, in which case the secure URL generated
292 // above won't actually start with https://
293 if ( substr( $url, 0, 8 ) === 'https://' ) {
294 $this->mSecureLoginUrl = $url;
295 }
296 }
297 }
298
299 if ( !$this->isActionAllowed( $this->authAction ) ) {
300 // FIXME how do we explain this to the user? can we handle session loss better?
301 // messages used: authpage-cannot-login, authpage-cannot-login-continue,
302 // authpage-cannot-create, authpage-cannot-create-continue
303 $this->mainLoginForm( [], 'authpage-cannot-' . $this->authAction );
304 return;
305 }
306
307 if ( $this->canBypassForm( $button_name ) ) {
308 $this->setRequest( [], true );
309 $this->getRequest()->setVal( $this->getTokenName(), $this->getToken() );
310 if ( $button_name ) {
311 $this->getRequest()->setVal( $button_name, true );
312 }
313 }
314
315 $status = $this->trySubmit();
316
317 if ( !$status || !$status->isGood() ) {
318 $this->mainLoginForm( $this->authRequests, $status ? $status->getMessage() : '', 'error' );
319 return;
320 }
321
322 /** @var AuthenticationResponse $response */
323 $response = $status->getValue();
324
325 $returnToUrl = $this->getPageTitle( 'return' )
326 ->getFullURL( $this->getPreservedParams( true ), false, PROTO_HTTPS );
327 switch ( $response->status ) {
328 case AuthenticationResponse::PASS:
329 $this->logAuthResult( true );
330 $this->proxyAccountCreation = $this->isSignup() && !$this->getUser()->isAnon();
331 $this->targetUser = User::newFromName( $response->username );
332
333 if (
334 !$this->proxyAccountCreation
335 && $response->loginRequest
336 && $authManager->canAuthenticateNow()
337 ) {
338 // successful registration; log the user in instantly
339 $response2 = $authManager->beginAuthentication( [ $response->loginRequest ],
340 $returnToUrl );
341 if ( $response2->status !== AuthenticationResponse::PASS ) {
342 LoggerFactory::getInstance( 'login' )
343 ->error( 'Could not log in after account creation' );
344 $this->successfulAction( true, Status::newFatal( 'createacct-loginerror' ) );
345 break;
346 }
347 }
348
349 if ( !$this->proxyAccountCreation ) {
350 // Ensure that the context user is the same as the session user.
351 $this->setSessionUserForCurrentRequest();
352 }
353
354 $this->successfulAction( true );
355 break;
356 case AuthenticationResponse::FAIL:
357 // fall through
358 case AuthenticationResponse::RESTART:
359 unset( $this->authForm );
360 if ( $response->status === AuthenticationResponse::FAIL ) {
361 $action = $this->getDefaultAction( $subPage );
362 $messageType = 'error';
363 } else {
364 $action = $this->getContinueAction( $this->authAction );
365 $messageType = 'warning';
366 }
367 $this->logAuthResult( false, $response->message ? $response->message->getKey() : '-' );
368 $this->loadAuth( $subPage, $action, true );
369 $this->mainLoginForm( $this->authRequests, $response->message, $messageType );
370 break;
371 case AuthenticationResponse::REDIRECT:
372 unset( $this->authForm );
373 $this->getOutput()->redirect( $response->redirectTarget );
374 break;
375 case AuthenticationResponse::UI:
376 unset( $this->authForm );
377 $this->authAction = $this->isSignup() ? AuthManager::ACTION_CREATE_CONTINUE
378 : AuthManager::ACTION_LOGIN_CONTINUE;
379 $this->authRequests = $response->neededRequests;
380 $this->mainLoginForm( $response->neededRequests, $response->message, $response->messageType );
381 break;
382 default:
383 throw new LogicException( 'invalid AuthenticationResponse' );
384 }
385 }
386
387 /**
388 * Determine if the login form can be bypassed. This will be the case when no more than one
389 * button is present and no other user input fields that are not marked as 'skippable' are
390 * present. If the login form were not bypassed, the user would be presented with a
391 * superfluous page on which they must press the single button to proceed with login.
392 * Not only does this cause an additional mouse click and page load, it confuses users,
393 * especially since there are a help link and forgotten password link that are
394 * provided on the login page that do not apply to this situation.
395 *
396 * @param string|null &$button_name if the form has a single button, returns
397 * the name of the button; otherwise, returns null
398 * @return bool
399 */
400 private function canBypassForm( &$button_name ) {
401 $button_name = null;
402 if ( $this->isContinued() ) {
403 return false;
404 }
405 $fields = AuthenticationRequest::mergeFieldInfo( $this->authRequests );
406 foreach ( $fields as $fieldname => $field ) {
407 if ( !isset( $field['type'] ) ) {
408 return false;
409 }
410 if ( !empty( $field['skippable'] ) ) {
411 continue;
412 }
413 if ( $field['type'] === 'button' ) {
414 if ( $button_name !== null ) {
415 $button_name = null;
416 return false;
417 } else {
418 $button_name = $fieldname;
419 }
420 } elseif ( $field['type'] !== 'null' ) {
421 return false;
422 }
423 }
424 return true;
425 }
426
427 /**
428 * Show the success page.
429 *
430 * @param string $type Condition of return to; see `executeReturnTo`
431 * @param string|Message $title Page's title
432 * @param string $msgname
433 * @param string $injected_html
434 * @param StatusValue|null $extraMessages
435 */
436 protected function showSuccessPage(
437 $type, $title, $msgname, $injected_html, $extraMessages
438 ) {
439 $out = $this->getOutput();
440 $out->setPageTitle( $title );
441 if ( $msgname ) {
442 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
443 }
444 if ( $extraMessages ) {
445 $extraMessages = Status::wrap( $extraMessages );
446 $out->addWikiTextAsInterface( $extraMessages->getWikiText() );
447 }
448
449 $out->addHTML( $injected_html );
450
451 $helper = new LoginHelper( $this->getContext() );
452 $helper->showReturnToPage( $type, $this->mReturnTo, $this->mReturnToQuery, $this->mStickHTTPS );
453 }
454
455 /**
456 * Add a "return to" link or redirect to it.
457 * Extensions can use this to reuse the "return to" logic after
458 * inject steps (such as redirection) into the login process.
459 *
460 * @param string $type One of the following:
461 * - error: display a return to link ignoring $wgRedirectOnLogin
462 * - signup: display a return to link using $wgRedirectOnLogin if needed
463 * - success: display a return to link using $wgRedirectOnLogin if needed
464 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
465 * @param string $returnTo
466 * @param array|string $returnToQuery
467 * @param bool $stickHTTPS Keep redirect link on HTTPS
468 * @since 1.22
469 */
470 public function showReturnToPage(
471 $type, $returnTo = '', $returnToQuery = '', $stickHTTPS = false
472 ) {
473 $helper = new LoginHelper( $this->getContext() );
474 $helper->showReturnToPage( $type, $returnTo, $returnToQuery, $stickHTTPS );
475 }
476
477 /**
478 * Replace some globals to make sure the fact that the user has just been logged in is
479 * reflected in the current request.
480 */
481 protected function setSessionUserForCurrentRequest() {
482 global $wgUser, $wgLang;
483
484 $context = RequestContext::getMain();
485 $localContext = $this->getContext();
486 if ( $context !== $localContext ) {
487 // remove AuthManagerSpecialPage context hack
488 $this->setContext( $context );
489 }
490
491 $user = $context->getRequest()->getSession()->getUser();
492
493 $wgUser = $user;
494 $context->setUser( $user );
495
496 $wgLang = $context->getLanguage();
497 }
498
499 /**
500 * @param AuthenticationRequest[] $requests A list of AuthorizationRequest objects,
501 * used to generate the form fields. An empty array means a fatal error
502 * (authentication cannot continue).
503 * @param string|Message $msg
504 * @param string $msgtype
505 * @throws ErrorPageError
506 * @throws Exception
507 * @throws FatalError
508 * @throws MWException
509 * @throws PermissionsError
510 * @throws ReadOnlyError
511 * @private
512 */
513 protected function mainLoginForm( array $requests, $msg = '', $msgtype = 'error' ) {
514 $user = $this->getUser();
515 $out = $this->getOutput();
516
517 // FIXME how to handle empty $requests - restart, or no form, just an error message?
518 // no form would be better for no session type errors, restart is better when can* fails.
519 if ( !$requests ) {
520 $this->authAction = $this->getDefaultAction( $this->subPage );
521 $this->authForm = null;
522 $requests = AuthManager::singleton()->getAuthenticationRequests( $this->authAction, $user );
523 }
524
525 // Generic styles and scripts for both login and signup form
526 $out->addModuleStyles( [
527 'mediawiki.ui',
528 'mediawiki.ui.button',
529 'mediawiki.ui.checkbox',
530 'mediawiki.ui.input',
531 'mediawiki.special.userlogin.common.styles'
532 ] );
533 if ( $this->isSignup() ) {
534 // XXX hack pending RL or JS parse() support for complex content messages T27349
535 $out->addJsConfigVars( 'wgCreateacctImgcaptchaHelp',
536 $this->msg( 'createacct-imgcaptcha-help' )->parse() );
537
538 // Additional styles and scripts for signup form
539 $out->addModules( [
540 'mediawiki.special.userlogin.signup.js'
541 ] );
542 $out->addModuleStyles( [
543 'mediawiki.special.userlogin.signup.styles'
544 ] );
545 } else {
546 // Additional styles for login form
547 $out->addModuleStyles( [
548 'mediawiki.special.userlogin.login.styles'
549 ] );
550 }
551 $out->disallowUserJs(); // just in case...
552
553 $form = $this->getAuthForm( $requests, $this->authAction, $msg, $msgtype );
554 $form->prepareForm();
555
556 $submitStatus = Status::newGood();
557 if ( $msg && $msgtype === 'warning' ) {
558 $submitStatus->warning( $msg );
559 } elseif ( $msg && $msgtype === 'error' ) {
560 $submitStatus->fatal( $msg );
561 }
562
563 // warning header for non-standard workflows (e.g. security reauthentication)
564 if (
565 !$this->isSignup() &&
566 $this->getUser()->isLoggedIn() &&
567 $this->authAction !== AuthManager::ACTION_LOGIN_CONTINUE
568 ) {
569 $reauthMessage = $this->securityLevel ? 'userlogin-reauth' : 'userlogin-loggedin';
570 $submitStatus->warning( $reauthMessage, $this->getUser()->getName() );
571 }
572
573 $formHtml = $form->getHTML( $submitStatus );
574
575 $out->addHTML( $this->getPageHtml( $formHtml ) );
576 }
577
578 /**
579 * Add page elements which are outside the form.
580 * FIXME this should probably be a template, but use a sane language (handlebars?)
581 * @param string $formHtml
582 * @return string
583 */
584 protected function getPageHtml( $formHtml ) {
585 global $wgLoginLanguageSelector;
586
587 $loginPrompt = $this->isSignup() ? '' : Html::rawElement( 'div',
588 [ 'id' => 'userloginprompt' ], $this->msg( 'loginprompt' )->parseAsBlock() );
589 $languageLinks = $wgLoginLanguageSelector ? $this->makeLanguageSelector() : '';
590 $signupStartMsg = $this->msg( 'signupstart' );
591 $signupStart = ( $this->isSignup() && !$signupStartMsg->isDisabled() )
592 ? Html::rawElement( 'div', [ 'id' => 'signupstart' ], $signupStartMsg->parseAsBlock() ) : '';
593 if ( $languageLinks ) {
594 $languageLinks = Html::rawElement( 'div', [ 'id' => 'languagelinks' ],
595 Html::rawElement( 'p', [], $languageLinks )
596 );
597 }
598
599 $benefitsContainer = '';
600 if ( $this->isSignup() && $this->showExtraInformation() ) {
601 // messages used:
602 // createacct-benefit-icon1 createacct-benefit-head1 createacct-benefit-body1
603 // createacct-benefit-icon2 createacct-benefit-head2 createacct-benefit-body2
604 // createacct-benefit-icon3 createacct-benefit-head3 createacct-benefit-body3
605 $benefitCount = 3;
606 $benefitList = '';
607 for ( $benefitIdx = 1; $benefitIdx <= $benefitCount; $benefitIdx++ ) {
608 $headUnescaped = $this->msg( "createacct-benefit-head$benefitIdx" )->text();
609 $iconClass = $this->msg( "createacct-benefit-icon$benefitIdx" )->text();
610 $benefitList .= Html::rawElement( 'div', [ 'class' => "mw-number-text $iconClass" ],
611 Html::rawElement( 'h3', [],
612 $this->msg( "createacct-benefit-head$benefitIdx" )->escaped()
613 )
614 . Html::rawElement( 'p', [],
615 $this->msg( "createacct-benefit-body$benefitIdx" )->params( $headUnescaped )->escaped()
616 )
617 );
618 }
619 $benefitsContainer = Html::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-container' ],
620 Html::rawElement( 'h2', [], $this->msg( 'createacct-benefit-heading' )->escaped() )
621 . Html::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-list' ],
622 $benefitList
623 )
624 );
625 }
626
627 $html = Html::rawElement( 'div', [ 'class' => 'mw-ui-container' ],
628 $loginPrompt
629 . $languageLinks
630 . $signupStart
631 . Html::rawElement( 'div', [ 'id' => 'userloginForm' ],
632 $formHtml
633 )
634 . $benefitsContainer
635 );
636
637 return $html;
638 }
639
640 /**
641 * Generates a form from the given request.
642 * @param AuthenticationRequest[] $requests
643 * @param string $action AuthManager action name
644 * @param string|Message $msg
645 * @param string $msgType
646 * @return HTMLForm
647 */
648 protected function getAuthForm( array $requests, $action, $msg = '', $msgType = 'error' ) {
649 global $wgSecureLogin;
650 // FIXME merge this with parent
651
652 if ( isset( $this->authForm ) ) {
653 return $this->authForm;
654 }
655
656 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
657
658 // get basic form description from the auth logic
659 $fieldInfo = AuthenticationRequest::mergeFieldInfo( $requests );
660 // this will call onAuthChangeFormFields()
661 $formDescriptor = static::fieldInfoToFormDescriptor( $requests, $fieldInfo, $this->authAction );
662 $this->postProcessFormDescriptor( $formDescriptor, $requests );
663
664 $context = $this->getContext();
665 if ( $context->getRequest() !== $this->getRequest() ) {
666 // We have overridden the request, need to make sure the form uses that too.
667 $context = new DerivativeContext( $this->getContext() );
668 $context->setRequest( $this->getRequest() );
669 }
670 $form = HTMLForm::factory( 'vform', $formDescriptor, $context );
671
672 $form->addHiddenField( 'authAction', $this->authAction );
673 if ( $this->mLanguage ) {
674 $form->addHiddenField( 'uselang', $this->mLanguage );
675 }
676 $form->addHiddenField( 'force', $this->securityLevel );
677 $form->addHiddenField( $this->getTokenName(), $this->getToken()->toString() );
678 if ( $wgSecureLogin ) {
679 // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
680 if ( !$this->isSignup() ) {
681 $form->addHiddenField( 'wpForceHttps', (int)$this->mStickHTTPS );
682 $form->addHiddenField( 'wpFromhttp', $usingHTTPS );
683 }
684 }
685
686 // set properties of the form itself
687 $form->setAction( $this->getPageTitle()->getLocalURL( $this->getReturnToQueryStringFragment() ) );
688 $form->setName( 'userlogin' . ( $this->isSignup() ? '2' : '' ) );
689 if ( $this->isSignup() ) {
690 $form->setId( 'userlogin2' );
691 }
692
693 $form->suppressDefaultSubmit();
694
695 $this->authForm = $form;
696
697 return $form;
698 }
699
700 public function onAuthChangeFormFields(
701 array $requests, array $fieldInfo, array &$formDescriptor, $action
702 ) {
703 $coreFieldDescriptors = $this->getFieldDefinitions();
704
705 // keep the ordering from getCoreFieldDescriptors() where there is no explicit weight
706 foreach ( $coreFieldDescriptors as $fieldName => $coreField ) {
707 $requestField = $formDescriptor[$fieldName] ?? [];
708
709 // remove everything that is not in the fieldinfo, is not marked as a supplemental field
710 // to something in the fieldinfo, and is not an info field or a submit button
711 if (
712 !isset( $fieldInfo[$fieldName] )
713 && (
714 !isset( $coreField['baseField'] )
715 || !isset( $fieldInfo[$coreField['baseField']] )
716 )
717 && (
718 !isset( $coreField['type'] )
719 || !in_array( $coreField['type'], [ 'submit', 'info' ], true )
720 )
721 ) {
722 $coreFieldDescriptors[$fieldName] = null;
723 continue;
724 }
725
726 // core message labels should always take priority
727 if (
728 isset( $coreField['label'] )
729 || isset( $coreField['label-message'] )
730 || isset( $coreField['label-raw'] )
731 ) {
732 unset( $requestField['label'], $requestField['label-message'], $coreField['label-raw'] );
733 }
734
735 $coreFieldDescriptors[$fieldName] += $requestField;
736 }
737
738 $formDescriptor = array_filter( $coreFieldDescriptors + $formDescriptor );
739 return true;
740 }
741
742 /**
743 * Show extra information such as password recovery information, link from login to signup,
744 * CTA etc? Such information should only be shown on the "landing page", ie. when the user
745 * is at the first step of the authentication process.
746 * @return bool
747 */
748 protected function showExtraInformation() {
749 return $this->authAction !== $this->getContinueAction( $this->authAction )
750 && !$this->securityLevel;
751 }
752
753 /**
754 * Create a HTMLForm descriptor for the core login fields.
755 * @return array
756 */
757 protected function getFieldDefinitions() {
758 global $wgEmailConfirmToEdit;
759
760 $isLoggedIn = $this->getUser()->isLoggedIn();
761 $continuePart = $this->isContinued() ? 'continue-' : '';
762 $anotherPart = $isLoggedIn ? 'another-' : '';
763 // @phan-suppress-next-line PhanUndeclaredMethod
764 $expiration = $this->getRequest()->getSession()->getProvider()->getRememberUserDuration();
765 $expirationDays = ceil( $expiration / ( 3600 * 24 ) );
766 $secureLoginLink = '';
767 if ( $this->mSecureLoginUrl ) {
768 $secureLoginLink = Html::element( 'a', [
769 'href' => $this->mSecureLoginUrl,
770 'class' => 'mw-ui-flush-right mw-secure',
771 ], $this->msg( 'userlogin-signwithsecure' )->text() );
772 }
773 $usernameHelpLink = '';
774 if ( !$this->msg( 'createacct-helpusername' )->isDisabled() ) {
775 $usernameHelpLink = Html::rawElement( 'span', [
776 'class' => 'mw-ui-flush-right',
777 ], $this->msg( 'createacct-helpusername' )->parse() );
778 }
779
780 if ( $this->isSignup() ) {
781 $fieldDefinitions = [
782 'statusarea' => [
783 // used by the mediawiki.special.userlogin.signup.js module for error display
784 // FIXME merge this with HTMLForm's normal status (error) area
785 'type' => 'info',
786 'raw' => true,
787 'default' => Html::element( 'div', [ 'id' => 'mw-createacct-status-area' ] ),
788 'weight' => -105,
789 ],
790 'username' => [
791 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $usernameHelpLink,
792 'id' => 'wpName2',
793 'placeholder-message' => $isLoggedIn ? 'createacct-another-username-ph'
794 : 'userlogin-yourname-ph',
795 ],
796 'mailpassword' => [
797 // create account without providing password, a temporary one will be mailed
798 'type' => 'check',
799 'label-message' => 'createaccountmail',
800 'name' => 'wpCreateaccountMail',
801 'id' => 'wpCreateaccountMail',
802 ],
803 'password' => [
804 'id' => 'wpPassword2',
805 'placeholder-message' => 'createacct-yourpassword-ph',
806 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
807 ],
808 'domain' => [],
809 'retype' => [
810 'baseField' => 'password',
811 'type' => 'password',
812 'label-message' => 'createacct-yourpasswordagain',
813 'id' => 'wpRetype',
814 'cssclass' => 'loginPassword',
815 'size' => 20,
816 'validation-callback' => function ( $value, $alldata ) {
817 if ( empty( $alldata['mailpassword'] ) && !empty( $alldata['password'] ) ) {
818 if ( !$value ) {
819 return $this->msg( 'htmlform-required' );
820 } elseif ( $value !== $alldata['password'] ) {
821 return $this->msg( 'badretype' );
822 }
823 }
824 return true;
825 },
826 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
827 'placeholder-message' => 'createacct-yourpasswordagain-ph',
828 ],
829 'email' => [
830 'type' => 'email',
831 'label-message' => $wgEmailConfirmToEdit ? 'createacct-emailrequired'
832 : 'createacct-emailoptional',
833 'id' => 'wpEmail',
834 'cssclass' => 'loginText',
835 'size' => '20',
836 // FIXME will break non-standard providers
837 'required' => $wgEmailConfirmToEdit,
838 'validation-callback' => function ( $value, $alldata ) {
839 global $wgEmailConfirmToEdit;
840
841 // AuthManager will check most of these, but that will make the auth
842 // session fail and this won't, so nicer to do it this way
843 if ( !$value && $wgEmailConfirmToEdit ) {
844 // no point in allowing registration without email when email is
845 // required to edit
846 return $this->msg( 'noemailtitle' );
847 } elseif ( !$value && !empty( $alldata['mailpassword'] ) ) {
848 // cannot send password via email when there is no email address
849 return $this->msg( 'noemailcreate' );
850 } elseif ( $value && !Sanitizer::validateEmail( $value ) ) {
851 return $this->msg( 'invalidemailaddress' );
852 }
853 return true;
854 },
855 'placeholder-message' => 'createacct-' . $anotherPart . 'email-ph',
856 ],
857 'realname' => [
858 'type' => 'text',
859 'help-message' => $isLoggedIn ? 'createacct-another-realname-tip'
860 : 'prefs-help-realname',
861 'label-message' => 'createacct-realname',
862 'cssclass' => 'loginText',
863 'size' => 20,
864 'id' => 'wpRealName',
865 ],
866 'reason' => [
867 // comment for the user creation log
868 'type' => 'text',
869 'label-message' => 'createacct-reason',
870 'cssclass' => 'loginText',
871 'id' => 'wpReason',
872 'size' => '20',
873 'placeholder-message' => 'createacct-reason-ph',
874 ],
875 'createaccount' => [
876 // submit button
877 'type' => 'submit',
878 'default' => $this->msg( 'createacct-' . $anotherPart . $continuePart .
879 'submit' )->text(),
880 'name' => 'wpCreateaccount',
881 'id' => 'wpCreateaccount',
882 'weight' => 100,
883 ],
884 ];
885 } else {
886 $fieldDefinitions = [
887 'username' => [
888 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $secureLoginLink,
889 'id' => 'wpName1',
890 'placeholder-message' => 'userlogin-yourname-ph',
891 ],
892 'password' => [
893 'id' => 'wpPassword1',
894 'placeholder-message' => 'userlogin-yourpassword-ph',
895 ],
896 'domain' => [],
897 'rememberMe' => [
898 // option for saving the user token to a cookie
899 'type' => 'check',
900 'name' => 'wpRemember',
901 'label-message' => $this->msg( 'userlogin-remembermypassword' )
902 ->numParams( $expirationDays ),
903 'id' => 'wpRemember',
904 ],
905 'loginattempt' => [
906 // submit button
907 'type' => 'submit',
908 'default' => $this->msg( 'pt-login-' . $continuePart . 'button' )->text(),
909 'id' => 'wpLoginAttempt',
910 'weight' => 100,
911 ],
912 'linkcontainer' => [
913 // help link
914 'type' => 'info',
915 'cssclass' => 'mw-form-related-link-container mw-userlogin-help',
916 // 'id' => 'mw-userlogin-help', // FIXME HTMLInfoField ignores this
917 'raw' => true,
918 'default' => Html::element( 'a', [
919 'href' => Skin::makeInternalOrExternalUrl( $this->msg( 'helplogin-url' )
920 ->inContentLanguage()
921 ->text() ),
922 ], $this->msg( 'userlogin-helplink2' )->text() ),
923 'weight' => 200,
924 ],
925 // button for ResetPasswordSecondaryAuthenticationProvider
926 'skipReset' => [
927 'weight' => 110,
928 'flags' => [],
929 ],
930 ];
931 }
932
933 $fieldDefinitions['username'] += [
934 'type' => 'text',
935 'name' => 'wpName',
936 'cssclass' => 'loginText',
937 'size' => 20,
938 // 'required' => true,
939 ];
940 $fieldDefinitions['password'] += [
941 'type' => 'password',
942 // 'label-message' => 'userlogin-yourpassword', // would override the changepassword label
943 'name' => 'wpPassword',
944 'cssclass' => 'loginPassword',
945 'size' => 20,
946 // 'required' => true,
947 ];
948
949 if ( $this->mEntryError ) {
950 $fieldDefinitions['entryError'] = [
951 'type' => 'info',
952 'default' => Html::rawElement( 'div', [ 'class' => $this->mEntryErrorType . 'box', ],
953 $this->mEntryError ),
954 'raw' => true,
955 'rawrow' => true,
956 'weight' => -100,
957 ];
958 }
959 if ( !$this->showExtraInformation() ) {
960 unset( $fieldDefinitions['linkcontainer'], $fieldDefinitions['signupend'] );
961 }
962 if ( $this->isSignup() && $this->showExtraInformation() ) {
963 // blank signup footer for site customization
964 // uses signupend-https for HTTPS requests if it's not blank, signupend otherwise
965 $signupendMsg = $this->msg( 'signupend' );
966 $signupendHttpsMsg = $this->msg( 'signupend-https' );
967 if ( !$signupendMsg->isDisabled() ) {
968 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
969 $signupendText = ( $usingHTTPS && !$signupendHttpsMsg->isBlank() )
970 ? $signupendHttpsMsg->parse() : $signupendMsg->parse();
971 $fieldDefinitions['signupend'] = [
972 'type' => 'info',
973 'raw' => true,
974 'default' => Html::rawElement( 'div', [ 'id' => 'signupend' ], $signupendText ),
975 'weight' => 225,
976 ];
977 }
978 }
979 if ( !$this->isSignup() && $this->showExtraInformation() ) {
980 $passwordReset = new PasswordReset( $this->getConfig(), AuthManager::singleton() );
981 if ( $passwordReset->isAllowed( $this->getUser() )->isGood() ) {
982 $fieldDefinitions['passwordReset'] = [
983 'type' => 'info',
984 'raw' => true,
985 'cssclass' => 'mw-form-related-link-container',
986 'default' => $this->getLinkRenderer()->makeLink(
987 SpecialPage::getTitleFor( 'PasswordReset' ),
988 $this->msg( 'userlogin-resetpassword-link' )->text()
989 ),
990 'weight' => 230,
991 ];
992 }
993
994 // Don't show a "create account" link if the user can't.
995 if ( $this->showCreateAccountLink() ) {
996 // link to the other action
997 $linkTitle = $this->getTitleFor( $this->isSignup() ? 'Userlogin' : 'CreateAccount' );
998 $linkq = $this->getReturnToQueryStringFragment();
999 // Pass any language selection on to the mode switch link
1000 if ( $this->mLanguage ) {
1001 $linkq .= '&uselang=' . urlencode( $this->mLanguage );
1002 }
1003 $loggedIn = $this->getUser()->isLoggedIn();
1004
1005 $fieldDefinitions['createOrLogin'] = [
1006 'type' => 'info',
1007 'raw' => true,
1008 'linkQuery' => $linkq,
1009 'default' => function ( $params ) use ( $loggedIn, $linkTitle ) {
1010 return Html::rawElement( 'div',
1011 [ 'id' => 'mw-createaccount' . ( !$loggedIn ? '-cta' : '' ),
1012 'class' => ( $loggedIn ? 'mw-form-related-link-container' : 'mw-ui-vform-field' ) ],
1013 ( $loggedIn ? '' : $this->msg( 'userlogin-noaccount' )->escaped() )
1014 . Html::element( 'a',
1015 [
1016 'id' => 'mw-createaccount-join' . ( $loggedIn ? '-loggedin' : '' ),
1017 'href' => $linkTitle->getLocalURL( $params['linkQuery'] ),
1018 'class' => ( $loggedIn ? '' : 'mw-ui-button' ),
1019 'tabindex' => 100,
1020 ],
1021 $this->msg(
1022 $loggedIn ? 'userlogin-createanother' : 'userlogin-joinproject'
1023 )->text()
1024 )
1025 );
1026 },
1027 'weight' => 235,
1028 ];
1029 }
1030 }
1031
1032 return $fieldDefinitions;
1033 }
1034
1035 /**
1036 * Check if a session cookie is present.
1037 *
1038 * This will not pick up a cookie set during _this_ request, but is meant
1039 * to ensure that the client is returning the cookie which was set on a
1040 * previous pass through the system.
1041 *
1042 * @return bool
1043 */
1044 protected function hasSessionCookie() {
1045 global $wgDisableCookieCheck, $wgInitialSessionId;
1046
1047 return $wgDisableCookieCheck || (
1048 $wgInitialSessionId &&
1049 $this->getRequest()->getSession()->getId() === (string)$wgInitialSessionId
1050 );
1051 }
1052
1053 /**
1054 * Returns a string that can be appended to the URL (without encoding) to preserve the
1055 * return target. Does not include leading '?'/'&'.
1056 * @return string
1057 */
1058 protected function getReturnToQueryStringFragment() {
1059 $returnto = '';
1060 if ( $this->mReturnTo !== '' ) {
1061 $returnto = 'returnto=' . wfUrlencode( $this->mReturnTo );
1062 if ( $this->mReturnToQuery !== '' ) {
1063 $returnto .= '&returntoquery=' . wfUrlencode( $this->mReturnToQuery );
1064 }
1065 }
1066 return $returnto;
1067 }
1068
1069 /**
1070 * Whether the login/create account form should display a link to the
1071 * other form (in addition to whatever the skin provides).
1072 * @return bool
1073 */
1074 private function showCreateAccountLink() {
1075 if ( $this->isSignup() ) {
1076 return true;
1077 } elseif ( $this->getUser()->isAllowed( 'createaccount' ) ) {
1078 return true;
1079 } else {
1080 return false;
1081 }
1082 }
1083
1084 protected function getTokenName() {
1085 return $this->isSignup() ? 'wpCreateaccountToken' : 'wpLoginToken';
1086 }
1087
1088 /**
1089 * Produce a bar of links which allow the user to select another language
1090 * during login/registration but retain "returnto"
1091 *
1092 * @return string
1093 */
1094 protected function makeLanguageSelector() {
1095 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1096 if ( $msg->isBlank() ) {
1097 return '';
1098 }
1099 $langs = explode( "\n", $msg->text() );
1100 $links = [];
1101 foreach ( $langs as $lang ) {
1102 $lang = trim( $lang, '* ' );
1103 $parts = explode( '|', $lang );
1104 if ( count( $parts ) >= 2 ) {
1105 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1106 }
1107 }
1108
1109 return count( $links ) > 0 ? $this->msg( 'loginlanguagelabel' )->rawParams(
1110 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1111 }
1112
1113 /**
1114 * Create a language selector link for a particular language
1115 * Links back to this page preserving type and returnto
1116 *
1117 * @param string $text Link text
1118 * @param string $lang Language code
1119 * @return string
1120 */
1121 protected function makeLanguageSelectorLink( $text, $lang ) {
1122 if ( $this->getLanguage()->getCode() == $lang ) {
1123 // no link for currently used language
1124 return htmlspecialchars( $text );
1125 }
1126 $query = [ 'uselang' => $lang ];
1127 if ( $this->mReturnTo !== '' ) {
1128 $query['returnto'] = $this->mReturnTo;
1129 $query['returntoquery'] = $this->mReturnToQuery;
1130 }
1131
1132 $attr = [];
1133 $targetLanguage = Language::factory( $lang );
1134 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1135
1136 return $this->getLinkRenderer()->makeKnownLink(
1137 $this->getPageTitle(),
1138 $text,
1139 $attr,
1140 $query
1141 );
1142 }
1143
1144 protected function getGroupName() {
1145 return 'login';
1146 }
1147
1148 /**
1149 * @param array &$formDescriptor
1150 * @param array $requests
1151 */
1152 protected function postProcessFormDescriptor( &$formDescriptor, $requests ) {
1153 // Pre-fill username (if not creating an account, T46775).
1154 if (
1155 isset( $formDescriptor['username'] ) &&
1156 !isset( $formDescriptor['username']['default'] ) &&
1157 !$this->isSignup()
1158 ) {
1159 $user = $this->getUser();
1160 if ( $user->isLoggedIn() ) {
1161 $formDescriptor['username']['default'] = $user->getName();
1162 } else {
1163 $formDescriptor['username']['default'] =
1164 $this->getRequest()->getSession()->suggestLoginUsername();
1165 }
1166 }
1167
1168 // don't show a submit button if there is nothing to submit (i.e. the only form content
1169 // is other submit buttons, for redirect flows)
1170 if ( !$this->needsSubmitButton( $requests ) ) {
1171 unset( $formDescriptor['createaccount'], $formDescriptor['loginattempt'] );
1172 }
1173
1174 if ( !$this->isSignup() ) {
1175 // FIXME HACK don't focus on non-empty field
1176 // maybe there should be an autofocus-if similar to hide-if?
1177 if (
1178 isset( $formDescriptor['username'] )
1179 && empty( $formDescriptor['username']['default'] )
1180 && !$this->getRequest()->getCheck( 'wpName' )
1181 ) {
1182 $formDescriptor['username']['autofocus'] = true;
1183 } elseif ( isset( $formDescriptor['password'] ) ) {
1184 $formDescriptor['password']['autofocus'] = true;
1185 }
1186 }
1187
1188 $this->addTabIndex( $formDescriptor );
1189 }
1190 }