3 use MediaWiki\Auth\AuthenticationRequest
;
4 use MediaWiki\Auth\AuthenticationResponse
;
5 use MediaWiki\Auth\AuthManager
;
6 use MediaWiki\Logger\LoggerFactory
;
7 use MediaWiki\Session\Token
;
10 * A special page subclass for authentication-related special pages. It generates a form from
11 * a set of AuthenticationRequest objects, submits the result to AuthManager and
12 * partially handles the response.
14 abstract class AuthManagerSpecialPage
extends SpecialPage
{
15 /** @var string[] The list of actions this special page deals with. Subclasses should override
18 protected static $allowedActions = [
19 AuthManager
::ACTION_LOGIN
, AuthManager
::ACTION_LOGIN_CONTINUE
,
20 AuthManager
::ACTION_CREATE
, AuthManager
::ACTION_CREATE_CONTINUE
,
21 AuthManager
::ACTION_LINK
, AuthManager
::ACTION_LINK_CONTINUE
,
22 AuthManager
::ACTION_CHANGE
, AuthManager
::ACTION_REMOVE
, AuthManager
::ACTION_UNLINK
,
25 /** @var array Customized messages */
26 protected static $messages = [];
28 /** @var string one of the AuthManager::ACTION_* constants. */
29 protected $authAction;
31 /** @var AuthenticationRequest[] */
32 protected $authRequests;
34 /** @var string Subpage of the special page. */
37 /** @var bool True if the current request is a result of returning from a redirect flow. */
40 /** @var WebRequest|null If set, will be used instead of the real request. Used for redirection. */
41 protected $savedRequest;
44 * Change the form descriptor that determines how a field will look in the authentication form.
45 * Called from fieldInfoToFormDescriptor().
46 * @param AuthenticationRequest[] $requests
47 * @param array $fieldInfo Field information array (union of all
48 * AuthenticationRequest::getFieldInfo() responses).
49 * @param array &$formDescriptor HTMLForm descriptor. The special key 'weight' can be set to
50 * change the order of the fields.
51 * @param string $action Authentication type (one of the AuthManager::ACTION_* constants)
54 public function onAuthChangeFormFields(
55 array $requests, array $fieldInfo, array &$formDescriptor, $action
60 protected function getLoginSecurityLevel() {
61 return $this->getName();
64 public function getRequest() {
65 return $this->savedRequest ?
: $this->getContext()->getRequest();
69 * Override the POST data, GET data from the real request is preserved.
71 * Used to preserve POST data over a HTTP redirect.
74 * @param bool|null $wasPosted
76 protected function setRequest( array $data, $wasPosted = null ) {
77 $request = $this->getContext()->getRequest();
78 if ( $wasPosted === null ) {
79 $wasPosted = $request->wasPosted();
81 $this->savedRequest
= new DerivativeRequest( $request, $data +
$request->getQueryValues(),
85 protected function beforeExecute( $subPage ) {
86 $this->getOutput()->disallowUserJs();
88 return $this->handleReturnBeforeExecute( $subPage )
89 && $this->handleReauthBeforeExecute( $subPage );
93 * Handle redirection from the /return subpage.
95 * This is used in the redirect flow where we need
96 * to be able to process data that was sent via a GET request. We set the /return subpage as
97 * the reentry point so we know we need to treat GET as POST, but we don't want to handle all
98 * future GETs as POSTs so we need to normalize the URL. (Also we don't want to show any
99 * received parameters around in the URL; they are ugly and might be sensitive.)
101 * Thus when on the /return subpage, we stash the request data in the session, redirect, then
102 * use the session to detect that we have been redirected, recover the data and replace the
103 * real WebRequest with a fake one that contains the saved data.
105 * @param string $subPage
106 * @return bool False if execution should be stopped.
108 protected function handleReturnBeforeExecute( $subPage ) {
109 $authManager = AuthManager
::singleton();
110 $key = 'AuthManagerSpecialPage:return:' . $this->getName();
112 if ( $subPage === 'return' ) {
113 $this->loadAuth( $subPage );
114 $preservedParams = $this->getPreservedParams( false );
116 // FIXME save POST values only from request
117 $authData = array_diff_key( $this->getRequest()->getValues(),
118 $preservedParams, [ 'title' => 1 ] );
119 $authManager->setAuthenticationSessionData( $key, $authData );
121 $url = $this->getPageTitle()->getFullURL( $preservedParams, false, PROTO_HTTPS
);
122 $this->getOutput()->redirect( $url );
126 $authData = $authManager->getAuthenticationSessionData( $key );
128 $authManager->removeAuthenticationSessionData( $key );
129 $this->isReturn
= true;
130 $this->setRequest( $authData, true );
137 * Handle redirection when the user needs to (re)authenticate.
139 * Send the user to the login form if needed; in case the request was a POST, stash in the
140 * session and simulate it once the user gets back.
142 * @param string $subPage
143 * @return bool False if execution should be stopped.
144 * @throws ErrorPageError When the user is not allowed to use this page.
146 protected function handleReauthBeforeExecute( $subPage ) {
147 $authManager = AuthManager
::singleton();
148 $request = $this->getRequest();
149 $key = 'AuthManagerSpecialPage:reauth:' . $this->getName();
151 $securityLevel = $this->getLoginSecurityLevel();
152 if ( $securityLevel ) {
153 $securityStatus = AuthManager
::singleton()
154 ->securitySensitiveOperationStatus( $securityLevel );
155 if ( $securityStatus === AuthManager
::SEC_REAUTH
) {
156 $queryParams = array_diff_key( $request->getQueryValues(), [ 'title' => true ] );
158 if ( $request->wasPosted() ) {
159 // unique ID in case the same special page is open in multiple browser tabs
160 $uniqueId = MWCryptRand
::generateHex( 6 );
161 $key .= ':' . $uniqueId;
163 $queryParams = [ 'authUniqueId' => $uniqueId ] +
$queryParams;
164 $authData = array_diff_key( $request->getValues(),
165 $this->getPreservedParams( false ), [ 'title' => 1 ] );
166 $authManager->setAuthenticationSessionData( $key, $authData );
169 $title = SpecialPage
::getTitleFor( 'Userlogin' );
170 $url = $title->getFullURL( [
171 'returnto' => $this->getFullTitle()->getPrefixedDBkey(),
172 'returntoquery' => wfArrayToCgi( $queryParams ),
173 'force' => $securityLevel,
174 ], false, PROTO_HTTPS
);
176 $this->getOutput()->redirect( $url );
178 } elseif ( $securityStatus !== AuthManager
::SEC_OK
) {
179 throw new ErrorPageError( 'cannotauth-not-allowed-title', 'cannotauth-not-allowed' );
183 $uniqueId = $request->getVal( 'authUniqueId' );
185 $key .= ':' . $uniqueId;
186 $authData = $authManager->getAuthenticationSessionData( $key );
188 $authManager->removeAuthenticationSessionData( $key );
189 $this->setRequest( $authData, true );
197 * Get the default action for this special page, if none is given via URL/POST data.
198 * Subclasses should override this (or override loadAuth() so this is never called).
199 * @param string $subPage Subpage of the special page.
200 * @return string an AuthManager::ACTION_* constant.
202 abstract protected function getDefaultAction( $subPage );
205 * Return custom message key.
206 * Allows subclasses to customize messages.
207 * @param string $defaultKey
210 protected function messageKey( $defaultKey ) {
211 return array_key_exists( $defaultKey, static::$messages )
212 ?
static::$messages[$defaultKey] : $defaultKey;
216 * Allows blacklisting certain request types.
217 * @return array A list of AuthenticationRequest subclass names
219 protected function getRequestBlacklist() {
224 * Load or initialize $authAction, $authRequests and $subPage.
225 * Subclasses should call this from execute() or otherwise ensure the variables are initialized.
226 * @param string $subPage Subpage of the special page.
227 * @param string|null $authAction Override auth action specified in request (this is useful
228 * when the form needs to be changed from <action> to <action>_CONTINUE after a successful
229 * authentication step)
230 * @param bool $reset Regenerate the requests even if a cached version is available
232 protected function loadAuth( $subPage, $authAction = null, $reset = false ) {
233 // Do not load if already loaded, to cut down on the number of getAuthenticationRequests
234 // calls. This is important for requests which have hidden information so any
235 // getAuthenticationRequests call would mean putting data into some cache.
237 !$reset && $this->subPage
=== $subPage && $this->authAction
238 && ( !$authAction ||
$authAction === $this->authAction
)
243 $request = $this->getRequest();
244 $this->subPage
= $subPage;
245 $this->authAction
= $authAction ?
: $request->getText( 'authAction' );
246 if ( !in_array( $this->authAction
, static::$allowedActions, true ) ) {
247 $this->authAction
= $this->getDefaultAction( $subPage );
248 if ( $request->wasPosted() ) {
249 $continueAction = $this->getContinueAction( $this->authAction
);
250 if ( in_array( $continueAction, static::$allowedActions, true ) ) {
251 $this->authAction
= $continueAction;
256 $allReqs = AuthManager
::singleton()->getAuthenticationRequests(
257 $this->authAction
, $this->getUser() );
258 $this->authRequests
= array_filter( $allReqs, function ( $req ) {
259 return !in_array( get_class( $req ), $this->getRequestBlacklist(), true );
264 * Returns true if this is not the first step of the authentication.
267 protected function isContinued() {
268 return in_array( $this->authAction
, [
269 AuthManager
::ACTION_LOGIN_CONTINUE
,
270 AuthManager
::ACTION_CREATE_CONTINUE
,
271 AuthManager
::ACTION_LINK_CONTINUE
,
276 * Gets the _CONTINUE version of an action.
277 * @param string $action An AuthManager::ACTION_* constant.
278 * @return string An AuthManager::ACTION_*_CONTINUE constant.
280 protected function getContinueAction( $action ) {
282 case AuthManager
::ACTION_LOGIN
:
283 $action = AuthManager
::ACTION_LOGIN_CONTINUE
;
285 case AuthManager
::ACTION_CREATE
:
286 $action = AuthManager
::ACTION_CREATE_CONTINUE
;
288 case AuthManager
::ACTION_LINK
:
289 $action = AuthManager
::ACTION_LINK_CONTINUE
;
296 * Checks whether AuthManager is ready to perform the action.
297 * ACTION_CHANGE needs special verification (AuthManager::allowsAuthenticationData*) which is
298 * the caller's responsibility.
299 * @param string $action One of the AuthManager::ACTION_* constants in static::$allowedActions
301 * @throws LogicException if $action is invalid
303 protected function isActionAllowed( $action ) {
304 $authManager = AuthManager
::singleton();
305 if ( !in_array( $action, static::$allowedActions, true ) ) {
306 throw new InvalidArgumentException( 'invalid action: ' . $action );
309 // calling getAuthenticationRequests can be expensive, avoid if possible
310 $requests = ( $action === $this->authAction
) ?
$this->authRequests
311 : $authManager->getAuthenticationRequests( $action );
313 // no provider supports this action in the current state
318 case AuthManager
::ACTION_LOGIN
:
319 case AuthManager
::ACTION_LOGIN_CONTINUE
:
320 return $authManager->canAuthenticateNow();
321 case AuthManager
::ACTION_CREATE
:
322 case AuthManager
::ACTION_CREATE_CONTINUE
:
323 return $authManager->canCreateAccounts();
324 case AuthManager
::ACTION_LINK
:
325 case AuthManager
::ACTION_LINK_CONTINUE
:
326 return $authManager->canLinkAccounts();
327 case AuthManager
::ACTION_CHANGE
:
328 case AuthManager
::ACTION_REMOVE
:
329 case AuthManager
::ACTION_UNLINK
:
332 // should never reach here but makes static code analyzers happy
333 throw new InvalidArgumentException( 'invalid action: ' . $action );
338 * @param string $action One of the AuthManager::ACTION_* constants
339 * @param AuthenticationRequest[] $requests
340 * @return AuthenticationResponse
341 * @throws LogicException if $action is invalid
343 protected function performAuthenticationStep( $action, array $requests ) {
344 if ( !in_array( $action, static::$allowedActions, true ) ) {
345 throw new InvalidArgumentException( 'invalid action: ' . $action );
348 $authManager = AuthManager
::singleton();
349 $returnToUrl = $this->getPageTitle( 'return' )
350 ->getFullURL( $this->getPreservedParams( true ), false, PROTO_HTTPS
);
353 case AuthManager
::ACTION_LOGIN
:
354 return $authManager->beginAuthentication( $requests, $returnToUrl );
355 case AuthManager
::ACTION_LOGIN_CONTINUE
:
356 return $authManager->continueAuthentication( $requests );
357 case AuthManager
::ACTION_CREATE
:
358 return $authManager->beginAccountCreation( $this->getUser(), $requests,
360 case AuthManager
::ACTION_CREATE_CONTINUE
:
361 return $authManager->continueAccountCreation( $requests );
362 case AuthManager
::ACTION_LINK
:
363 return $authManager->beginAccountLink( $this->getUser(), $requests, $returnToUrl );
364 case AuthManager
::ACTION_LINK_CONTINUE
:
365 return $authManager->continueAccountLink( $requests );
366 case AuthManager
::ACTION_CHANGE
:
367 case AuthManager
::ACTION_REMOVE
:
368 case AuthManager
::ACTION_UNLINK
:
369 if ( count( $requests ) > 1 ) {
370 throw new InvalidArgumentException( 'only one auth request can be changed at a time' );
371 } elseif ( !$requests ) {
372 throw new InvalidArgumentException( 'no auth request' );
374 $req = reset( $requests );
375 $status = $authManager->allowsAuthenticationDataChange( $req );
376 Hooks
::run( 'ChangeAuthenticationDataAudit', [ $req, $status ] );
377 if ( !$status->isGood() ) {
378 return AuthenticationResponse
::newFail( $status->getMessage() );
380 $authManager->changeAuthenticationData( $req );
381 return AuthenticationResponse
::newPass();
383 // should never reach here but makes static code analyzers happy
384 throw new InvalidArgumentException( 'invalid action: ' . $action );
389 * Attempts to do an authentication step with the submitted data.
390 * Subclasses should probably call this from execute().
391 * @return false|Status
392 * - false if there was no submit at all
393 * - a good Status wrapping an AuthenticationResponse if the form submit was successful.
394 * This does not necessarily mean that the authentication itself was successful; see the
396 * - a bad Status for form errors.
398 protected function trySubmit() {
401 $form = $this->getAuthForm( $this->authRequests
, $this->authAction
);
402 $form->setSubmitCallback( [ $this, 'handleFormSubmit' ] );
404 if ( $this->getRequest()->wasPosted() ) {
405 // handle tokens manually; $form->tryAuthorizedSubmit only works for logged-in users
406 $requestTokenValue = $this->getRequest()->getVal( $this->getTokenName() );
407 $sessionToken = $this->getToken();
408 if ( $sessionToken->wasNew() ) {
409 return Status
::newFatal( $this->messageKey( 'authform-newtoken' ) );
410 } elseif ( !$requestTokenValue ) {
411 return Status
::newFatal( $this->messageKey( 'authform-notoken' ) );
412 } elseif ( !$sessionToken->match( $requestTokenValue ) ) {
413 return Status
::newFatal( $this->messageKey( 'authform-wrongtoken' ) );
416 $form->prepareForm();
417 $status = $form->trySubmit();
419 // HTMLForm submit return values are a mess; let's ensure it is false or a Status
420 // FIXME this probably should be in HTMLForm
421 if ( $status === true ) {
422 // not supposed to happen since our submit handler should always return a Status
423 throw new UnexpectedValueException( 'HTMLForm::trySubmit() returned true' );
424 } elseif ( $status === false ) {
425 // form was not submitted; nothing to do
426 } elseif ( $status instanceof Status
) {
427 // already handled by the form; nothing to do
428 } elseif ( $status instanceof StatusValue
) {
429 // in theory not an allowed return type but nothing stops the submit handler from
430 // accidentally returning it so best check and fix
431 $status = Status
::wrap( $status );
432 } elseif ( is_string( $status ) ) {
433 $status = Status
::newFatal( new RawMessage( '$1', [ $status ] ) );
434 } elseif ( is_array( $status ) ) {
435 if ( is_string( reset( $status ) ) ) {
436 $status = Status
::newFatal( ...$status );
437 } elseif ( is_array( reset( $status ) ) ) {
438 $ret = Status
::newGood();
439 foreach ( $status as $message ) {
440 $ret->fatal( ...$message );
444 throw new UnexpectedValueException( 'invalid HTMLForm::trySubmit() return value: '
445 . 'first element of array is ' . gettype( reset( $status ) ) );
448 // not supposed to happen but HTMLForm does not actually verify the return type
449 // from the submit callback; better safe then sorry
450 throw new UnexpectedValueException( 'invalid HTMLForm::trySubmit() return type: '
451 . gettype( $status ) );
454 if ( ( !$status ||
!$status->isOK() ) && $this->isReturn
) {
455 // This is awkward. There was a form validation error, which means the data was not
456 // passed to AuthManager. Normally we would display the form with an error message,
457 // but for the data we received via the redirect flow that would not be helpful at all.
458 // Let's just submit the data to AuthManager directly instead.
459 LoggerFactory
::getInstance( 'authentication' )
460 ->warning( 'Validation error on return', [ 'data' => $form->mFieldData
,
461 'status' => $status->getWikiText( false, false, 'en' ) ] );
462 $status = $this->handleFormSubmit( $form->mFieldData
);
467 AuthManager
::ACTION_CHANGE
, AuthManager
::ACTION_REMOVE
, AuthManager
::ACTION_UNLINK
469 if ( in_array( $this->authAction
, $changeActions, true ) && $status && !$status->isOK() ) {
470 Hooks
::run( 'ChangeAuthenticationDataAudit', [ reset( $this->authRequests
), $status ] );
477 * Submit handler callback for HTMLForm
479 * @param array $data Submitted data
482 public function handleFormSubmit( $data ) {
483 $requests = AuthenticationRequest
::loadRequestsFromSubmission( $this->authRequests
, $data );
484 $response = $this->performAuthenticationStep( $this->authAction
, $requests );
486 // we can't handle FAIL or similar as failure here since it might require changing the form
487 return Status
::newGood( $response );
491 * Returns URL query parameters which can be used to reload the page (or leave and return) while
492 * preserving all information that is necessary for authentication to continue. These parameters
493 * will be preserved in the action URL of the form and in the return URL for redirect flow.
494 * @param bool $withToken Include CSRF token
497 protected function getPreservedParams( $withToken = false ) {
499 if ( $this->authAction
!== $this->getDefaultAction( $this->subPage
) ) {
500 $params['authAction'] = $this->getContinueAction( $this->authAction
);
503 $params[$this->getTokenName()] = $this->getToken()->toString();
509 * Generates a HTMLForm descriptor array from a set of authentication requests.
510 * @param AuthenticationRequest[] $requests
511 * @param string $action AuthManager action name (one of the AuthManager::ACTION_* constants)
514 protected function getAuthFormDescriptor( $requests, $action ) {
515 $fieldInfo = AuthenticationRequest
::mergeFieldInfo( $requests );
516 $formDescriptor = $this->fieldInfoToFormDescriptor( $requests, $fieldInfo, $action );
518 $this->addTabIndex( $formDescriptor );
520 return $formDescriptor;
524 * @param AuthenticationRequest[] $requests
525 * @param string $action AuthManager action name (one of the AuthManager::ACTION_* constants)
528 protected function getAuthForm( array $requests, $action ) {
529 $formDescriptor = $this->getAuthFormDescriptor( $requests, $action );
530 $context = $this->getContext();
531 if ( $context->getRequest() !== $this->getRequest() ) {
532 // We have overridden the request, need to make sure the form uses that too.
533 $context = new DerivativeContext( $this->getContext() );
534 $context->setRequest( $this->getRequest() );
536 $form = HTMLForm
::factory( 'ooui', $formDescriptor, $context );
537 $form->setAction( $this->getFullTitle()->getFullURL( $this->getPreservedParams() ) );
538 $form->addHiddenField( $this->getTokenName(), $this->getToken()->toString() );
539 $form->addHiddenField( 'authAction', $this->authAction
);
540 $form->suppressDefaultSubmit( !$this->needsSubmitButton( $requests ) );
547 * @param false|Status|StatusValue $status A form submit status, as in HTMLForm::trySubmit()
549 protected function displayForm( $status ) {
550 if ( $status instanceof StatusValue
) {
551 $status = Status
::wrap( $status );
553 $form = $this->getAuthForm( $this->authRequests
, $this->authAction
);
554 $form->prepareForm()->displayForm( $status );
558 * Returns true if the form built from the given AuthenticationRequests needs a submit button.
559 * Providers using redirect flow (e.g. Google login) need their own submit buttons; if using
560 * one of those custom buttons is the only way to proceed, there is no point in displaying the
561 * default button which won't do anything useful.
563 * @param AuthenticationRequest[] $requests An array of AuthenticationRequests from which the
567 protected function needsSubmitButton( array $requests ) {
568 $customSubmitButtonPresent = false;
570 // Secondary and preauth providers always need their data; they will not care what button
571 // is used, so they can be ignored. So can OPTIONAL buttons createdby primary providers;
572 // that's the point in being optional. Se we need to check whether all primary providers
573 // have their own buttons and whether there is at least one button present.
574 foreach ( $requests as $req ) {
575 if ( $req->required
=== AuthenticationRequest
::PRIMARY_REQUIRED
) {
576 if ( $this->hasOwnSubmitButton( $req ) ) {
577 $customSubmitButtonPresent = true;
583 return !$customSubmitButtonPresent;
587 * Checks whether the given AuthenticationRequest has its own submit button.
588 * @param AuthenticationRequest $req
591 protected function hasOwnSubmitButton( AuthenticationRequest
$req ) {
592 foreach ( $req->getFieldInfo() as $field => $info ) {
593 if ( $info['type'] === 'button' ) {
601 * Adds a sequential tabindex starting from 1 to all form elements. This way the user can
602 * use the tab key to traverse the form without having to step through all links and such.
603 * @param array[] &$formDescriptor
605 protected function addTabIndex( &$formDescriptor ) {
607 foreach ( $formDescriptor as $field => &$definition ) {
609 if ( array_key_exists( 'class', $definition ) ) {
610 $class = $definition['class'];
611 } elseif ( array_key_exists( 'type', $definition ) ) {
612 $class = HTMLForm
::$typeMappings[$definition['type']];
614 if ( $class !== HTMLInfoField
::class ) {
615 $definition['tabindex'] = $i;
622 * Returns the CSRF token.
625 protected function getToken() {
626 return $this->getRequest()->getSession()->getToken( 'AuthManagerSpecialPage:'
627 . $this->getName() );
631 * Returns the name of the CSRF token (under which it should be found in the POST or GET data).
634 protected function getTokenName() {
635 return 'wpAuthToken';
639 * Turns a field info array into a form descriptor. Behavior can be modified by the
640 * AuthChangeFormFields hook.
641 * @param AuthenticationRequest[] $requests
642 * @param array $fieldInfo Field information, in the format used by
643 * AuthenticationRequest::getFieldInfo()
644 * @param string $action One of the AuthManager::ACTION_* constants
645 * @return array A form descriptor that can be passed to HTMLForm
647 protected function fieldInfoToFormDescriptor( array $requests, array $fieldInfo, $action ) {
648 $formDescriptor = [];
649 foreach ( $fieldInfo as $fieldName => $singleFieldInfo ) {
650 $formDescriptor[$fieldName] = self
::mapSingleFieldInfo( $singleFieldInfo, $fieldName );
653 $requestSnapshot = serialize( $requests );
654 $this->onAuthChangeFormFields( $requests, $fieldInfo, $formDescriptor, $action );
655 \Hooks
::run( 'AuthChangeFormFields', [ $requests, $fieldInfo, &$formDescriptor, $action ] );
656 if ( $requestSnapshot !== serialize( $requests ) ) {
657 LoggerFactory
::getInstance( 'authentication' )->warning(
658 'AuthChangeFormFields hook changed auth requests' );
661 // Process the special 'weight' property, which is a way for AuthChangeFormFields hook
662 // subscribers (who only see one field at a time) to influence ordering.
663 self
::sortFormDescriptorFields( $formDescriptor );
665 return $formDescriptor;
669 * Maps an authentication field configuration for a single field (as returned by
670 * AuthenticationRequest::getFieldInfo()) to a HTMLForm field descriptor.
671 * @param array $singleFieldInfo
672 * @param string $fieldName
675 protected static function mapSingleFieldInfo( $singleFieldInfo, $fieldName ) {
676 $type = self
::mapFieldInfoTypeToFormDescriptorType( $singleFieldInfo['type'] );
679 // Do not prefix input name with 'wp'. This is important for the redirect flow.
680 'name' => $fieldName,
683 if ( $type === 'submit' && isset( $singleFieldInfo['label'] ) ) {
684 $descriptor['default'] = $singleFieldInfo['label']->plain();
685 } elseif ( $type !== 'submit' ) {
686 $descriptor +
= array_filter( [
687 // help-message is omitted as it is usually not really useful for a web interface
688 'label-message' => self
::getField( $singleFieldInfo, 'label' ),
691 if ( isset( $singleFieldInfo['options'] ) ) {
692 $descriptor['options'] = array_flip( array_map( function ( $message ) {
693 /** @var Message $message */
694 return $message->parse();
695 }, $singleFieldInfo['options'] ) );
698 if ( isset( $singleFieldInfo['value'] ) ) {
699 $descriptor['default'] = $singleFieldInfo['value'];
702 if ( empty( $singleFieldInfo['optional'] ) ) {
703 $descriptor['required'] = true;
711 * Sort the fields of a form descriptor by their 'weight' property. (Fields with higher weight
712 * are shown closer to the bottom; weight defaults to 0. Negative weight is allowed.)
713 * Keep order if weights are equal.
714 * @param array &$formDescriptor
716 protected static function sortFormDescriptorFields( array &$formDescriptor ) {
718 foreach ( $formDescriptor as &$field ) {
719 $field['__index'] = $i++
;
721 uasort( $formDescriptor, function ( $first, $second ) {
722 return self
::getField( $first, 'weight', 0 ) <=> self
::getField( $second, 'weight', 0 )
723 ?
: $first['__index'] <=> $second['__index'];
725 foreach ( $formDescriptor as &$field ) {
726 unset( $field['__index'] );
731 * Get an array value, or a default if it does not exist.
732 * @param array $array
733 * @param string $fieldName
734 * @param mixed|null $default
737 protected static function getField( array $array, $fieldName, $default = null ) {
738 if ( array_key_exists( $fieldName, $array ) ) {
739 return $array[$fieldName];
746 * Maps AuthenticationRequest::getFieldInfo() types to HTMLForm types
747 * @param string $type
749 * @throws \LogicException
751 protected static function mapFieldInfoTypeToFormDescriptorType( $type ) {
754 'password' => 'password',
755 'select' => 'select',
756 'checkbox' => 'check',
757 'multiselect' => 'multiselect',
758 'button' => 'submit',
759 'hidden' => 'hidden',
762 if ( !array_key_exists( $type, $map ) ) {
763 throw new \
LogicException( 'invalid field type: ' . $type );