Expose $wgMaxArticleSize in siteinfo query api
[mediawiki.git] / includes / specialpage / AuthManagerSpecialPage.php
blob9833c73be1a8caf7e131e59b629eca28b12e926b
1 <?php
3 use MediaWiki\Auth\AuthenticationRequest;
4 use MediaWiki\Auth\AuthenticationResponse;
5 use MediaWiki\Auth\AuthManager;
6 use MediaWiki\Logger\LoggerFactory;
7 use MediaWiki\Session\SessionManager;
8 use MediaWiki\Session\Token;
10 /**
11 * A special page subclass for authentication-related special pages. It generates a form from
12 * a set of AuthenticationRequest objects, submits the result to AuthManager and
13 * partially handles the response.
15 abstract class AuthManagerSpecialPage extends SpecialPage {
16 /** @var string[] The list of actions this special page deals with. Subclasses should override
17 * this. */
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. */
35 protected $subPage;
37 /** @var bool True if the current request is a result of returning from a redirect flow. */
38 protected $isReturn;
40 /** @var WebRequest|null If set, will be used instead of the real request. Used for redirection. */
41 protected $savedRequest;
43 /**
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 string $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)
52 * @return bool
54 public function onAuthChangeFormFields(
55 array $requests, array $fieldInfo, array &$formDescriptor, $action
56 ) {
57 return true;
60 protected function getLoginSecurityLevel() {
61 return $this->getName();
64 public function getRequest() {
65 return $this->savedRequest ?: $this->getContext()->getRequest();
68 /**
69 * Override the POST data, GET data from the real request is preserved.
71 * Used to preserve POST data over a HTTP redirect.
73 * @param array $data
74 * @param bool $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(),
82 $wasPosted );
85 protected function beforeExecute( $subPage ) {
86 $this->getOutput()->disallowUserJs();
88 return $this->handleReturnBeforeExecute( $subPage )
89 && $this->handleReauthBeforeExecute( $subPage );
92 /**
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 );
123 return false;
126 $authData = $authManager->getAuthenticationSessionData( $key );
127 if ( $authData ) {
128 $authManager->removeAuthenticationSessionData( $key );
129 $this->isReturn = true;
130 $this->setRequest( $authData, true );
133 return 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 = $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 );
177 return false;
178 } elseif ( $securityStatus !== AuthManager::SEC_OK ) {
179 throw new ErrorPageError( 'cannotauth-not-allowed-title', 'cannotauth-not-allowed' );
183 $uniqueId = $request->getVal( 'authUniqueId' );
184 if ( $uniqueId ) {
185 $key = $key . ':' . $uniqueId;
186 $authData = $authManager->getAuthenticationSessionData( $key );
187 if ( $authData ) {
188 $authManager->removeAuthenticationSessionData( $key );
189 $this->setRequest( $authData, true );
193 return 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 protected function getDefaultAction( $subPage ) {
203 throw new BadMethodCallException( 'Subclass did not implement getDefaultAction' );
207 * Return custom message key.
208 * Allows subclasses to customize messages.
209 * @return string
211 protected function messageKey( $defaultKey ) {
212 return array_key_exists( $defaultKey, static::$messages )
213 ? static::$messages[$defaultKey] : $defaultKey;
217 * Allows blacklisting certain request types.
218 * @return array A list of AuthenticationRequest subclass names
220 protected function getRequestBlacklist() {
221 return [];
225 * Load or initialize $authAction, $authRequests and $subPage.
226 * Subclasses should call this from execute() or otherwise ensure the variables are initialized.
227 * @param string $subPage Subpage of the special page.
228 * @param string $authAction Override auth action specified in request (this is useful
229 * when the form needs to be changed from <action> to <action>_CONTINUE after a successful
230 * authentication step)
231 * @param bool $reset Regenerate the requests even if a cached version is available
233 protected function loadAuth( $subPage, $authAction = null, $reset = false ) {
234 // Do not load if already loaded, to cut down on the number of getAuthenticationRequests
235 // calls. This is important for requests which have hidden information so any
236 // getAuthenticationRequests call would mean putting data into some cache.
237 if (
238 !$reset && $this->subPage === $subPage && $this->authAction
239 && ( !$authAction || $authAction === $this->authAction )
241 return;
244 $request = $this->getRequest();
245 $this->subPage = $subPage;
246 $this->authAction = $authAction ?: $request->getText( 'authAction' );
247 if ( !in_array( $this->authAction, static::$allowedActions, true ) ) {
248 $this->authAction = $this->getDefaultAction( $subPage );
249 if ( $request->wasPosted() ) {
250 $continueAction = $this->getContinueAction( $this->authAction );
251 if ( in_array( $continueAction, static::$allowedActions, true ) ) {
252 $this->authAction = $continueAction;
257 $allReqs = AuthManager::singleton()->getAuthenticationRequests(
258 $this->authAction, $this->getUser() );
259 $this->authRequests = array_filter( $allReqs, function ( $req ) use ( $subPage ) {
260 return !in_array( get_class( $req ), $this->getRequestBlacklist(), true );
261 } );
265 * Returns true if this is not the first step of the authentication.
266 * @return bool
268 protected function isContinued() {
269 return in_array( $this->authAction, [
270 AuthManager::ACTION_LOGIN_CONTINUE,
271 AuthManager::ACTION_CREATE_CONTINUE,
272 AuthManager::ACTION_LINK_CONTINUE,
273 ], true );
277 * Gets the _CONTINUE version of an action.
278 * @param string $action An AuthManager::ACTION_* constant.
279 * @return string An AuthManager::ACTION_*_CONTINUE constant.
281 protected function getContinueAction( $action ) {
282 switch ( $action ) {
283 case AuthManager::ACTION_LOGIN:
284 $action = AuthManager::ACTION_LOGIN_CONTINUE;
285 break;
286 case AuthManager::ACTION_CREATE:
287 $action = AuthManager::ACTION_CREATE_CONTINUE;
288 break;
289 case AuthManager::ACTION_LINK:
290 $action = AuthManager::ACTION_LINK_CONTINUE;
291 break;
293 return $action;
297 * Checks whether AuthManager is ready to perform the action.
298 * ACTION_CHANGE needs special verification (AuthManager::allowsAuthenticationData*) which is
299 * the caller's responsibility.
300 * @param string $action One of the AuthManager::ACTION_* constants in static::$allowedActions
301 * @return bool
302 * @throws LogicException if $action is invalid
304 protected function isActionAllowed( $action ) {
305 $authManager = AuthManager::singleton();
306 if ( !in_array( $action, static::$allowedActions, true ) ) {
307 throw new InvalidArgumentException( 'invalid action: ' . $action );
310 // calling getAuthenticationRequests can be expensive, avoid if possible
311 $requests = ( $action === $this->authAction ) ? $this->authRequests
312 : $authManager->getAuthenticationRequests( $action );
313 if ( !$requests ) {
314 // no provider supports this action in the current state
315 return false;
318 switch ( $action ) {
319 case AuthManager::ACTION_LOGIN:
320 case AuthManager::ACTION_LOGIN_CONTINUE:
321 return $authManager->canAuthenticateNow();
322 case AuthManager::ACTION_CREATE:
323 case AuthManager::ACTION_CREATE_CONTINUE:
324 return $authManager->canCreateAccounts();
325 case AuthManager::ACTION_LINK:
326 case AuthManager::ACTION_LINK_CONTINUE:
327 return $authManager->canLinkAccounts();
328 case AuthManager::ACTION_CHANGE:
329 case AuthManager::ACTION_REMOVE:
330 case AuthManager::ACTION_UNLINK:
331 return true;
332 default:
333 // should never reach here but makes static code analyzers happy
334 throw new InvalidArgumentException( 'invalid action: ' . $action );
339 * @param string $action One of the AuthManager::ACTION_* constants
340 * @param AuthenticationRequest[] $requests
341 * @return AuthenticationResponse
342 * @throws LogicException if $action is invalid
344 protected function performAuthenticationStep( $action, array $requests ) {
345 if ( !in_array( $action, static::$allowedActions, true ) ) {
346 throw new InvalidArgumentException( 'invalid action: ' . $action );
349 $authManager = AuthManager::singleton();
350 $returnToUrl = $this->getPageTitle( 'return' )
351 ->getFullURL( $this->getPreservedParams( true ), false, PROTO_HTTPS );
353 switch ( $action ) {
354 case AuthManager::ACTION_LOGIN:
355 return $authManager->beginAuthentication( $requests, $returnToUrl );
356 case AuthManager::ACTION_LOGIN_CONTINUE:
357 return $authManager->continueAuthentication( $requests );
358 case AuthManager::ACTION_CREATE:
359 return $authManager->beginAccountCreation( $this->getUser(), $requests,
360 $returnToUrl );
361 case AuthManager::ACTION_CREATE_CONTINUE:
362 return $authManager->continueAccountCreation( $requests );
363 case AuthManager::ACTION_LINK:
364 return $authManager->beginAccountLink( $this->getUser(), $requests, $returnToUrl );
365 case AuthManager::ACTION_LINK_CONTINUE:
366 return $authManager->continueAccountLink( $requests );
367 case AuthManager::ACTION_CHANGE:
368 case AuthManager::ACTION_REMOVE:
369 case AuthManager::ACTION_UNLINK:
370 if ( count( $requests ) > 1 ) {
371 throw new InvalidArgumentException( 'only one auth request can be changed at a time' );
372 } elseif ( !$requests ) {
373 throw new InvalidArgumentException( 'no auth request' );
375 $req = reset( $requests );
376 $status = $authManager->allowsAuthenticationDataChange( $req );
377 Hooks::run( 'ChangeAuthenticationDataAudit', [ $req, $status ] );
378 if ( !$status->isGood() ) {
379 return AuthenticationResponse::newFail( $status->getMessage() );
381 $authManager->changeAuthenticationData( $req );
382 return AuthenticationResponse::newPass();
383 default:
384 // should never reach here but makes static code analyzers happy
385 throw new InvalidArgumentException( 'invalid action: ' . $action );
390 * Attempts to do an authentication step with the submitted data.
391 * Subclasses should probably call this from execute().
392 * @return false|Status
393 * - false if there was no submit at all
394 * - a good Status wrapping an AuthenticationResponse if the form submit was successful.
395 * This does not necessarily mean that the authentication itself was successful; see the
396 * response for that.
397 * - a bad Status for form errors.
399 protected function trySubmit() {
400 $status = false;
402 $form = $this->getAuthForm( $this->authRequests, $this->authAction );
403 $form->setSubmitCallback( [ $this, 'handleFormSubmit' ] );
405 if ( $this->getRequest()->wasPosted() ) {
406 // handle tokens manually; $form->tryAuthorizedSubmit only works for logged-in users
407 $requestTokenValue = $this->getRequest()->getVal( $this->getTokenName() );
408 $sessionToken = $this->getToken();
409 if ( $sessionToken->wasNew() ) {
410 return Status::newFatal( $this->messageKey( 'authform-newtoken' ) );
411 } elseif ( !$requestTokenValue ) {
412 return Status::newFatal( $this->messageKey( 'authform-notoken' ) );
413 } elseif ( !$sessionToken->match( $requestTokenValue ) ) {
414 return Status::newFatal( $this->messageKey( 'authform-wrongtoken' ) );
417 $form->prepareForm();
418 $status = $form->trySubmit();
420 // HTMLForm submit return values are a mess; let's ensure it is false or a Status
421 // FIXME this probably should be in HTMLForm
422 if ( $status === true ) {
423 // not supposed to happen since our submit handler should always return a Status
424 throw new UnexpectedValueException( 'HTMLForm::trySubmit() returned true' );
425 } elseif ( $status === false ) {
426 // form was not submitted; nothing to do
427 } elseif ( $status instanceof Status ) {
428 // already handled by the form; nothing to do
429 } elseif ( $status instanceof StatusValue ) {
430 // in theory not an allowed return type but nothing stops the submit handler from
431 // accidentally returning it so best check and fix
432 $status = Status::wrap( $status );
433 } elseif ( is_string( $status ) ) {
434 $status = Status::newFatal( new RawMessage( '$1', $status ) );
435 } elseif ( is_array( $status ) ) {
436 if ( is_string( reset( $status ) ) ) {
437 $status = call_user_func_array( 'Status::newFatal', $status );
438 } elseif ( is_array( reset( $status ) ) ) {
439 $status = Status::newGood();
440 foreach ( $status as $message ) {
441 call_user_func_array( [ $status, 'fatal' ], $message );
443 } else {
444 throw new UnexpectedValueException( 'invalid HTMLForm::trySubmit() return value: '
445 . 'first element of array is ' . gettype( reset( $status ) ) );
447 } else {
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( 'authmanager' )
460 ->warning( 'Validation error on return', [ 'data' => $form->mFieldData,
461 'status' => $status->getWikiText() ] );
462 $status = $this->handleFormSubmit( $form->mFieldData );
466 $changeActions = [
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 ] );
473 return $status;
477 * Submit handler callback for HTMLForm
478 * @private
479 * @param $data array Submitted data
480 * @return Status
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
495 * @return array
497 protected function getPreservedParams( $withToken = false ) {
498 $params = [];
499 if ( $this->authAction !== $this->getDefaultAction( $this->subPage ) ) {
500 $params['authAction'] = $this->getContinueAction( $this->authAction );
502 if ( $withToken ) {
503 $params[$this->getTokenName()] = $this->getToken()->toString();
505 return $params;
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)
512 * @return array
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)
526 * @return HTMLForm
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( $formDescriptor ) );
542 return $form;
546 * Display the form.
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 has fields which take values. If all available providers use the
559 * redirect flow, the form might contain nothing but submit buttons, in which case we should
560 * not add an extra submit button which does nothing.
562 * @param array $formDescriptor A HTMLForm descriptor
563 * @return bool
565 protected function needsSubmitButton( $formDescriptor ) {
566 return (bool)array_filter( $formDescriptor, function ( $item ) {
567 $class = false;
568 if ( array_key_exists( 'class', $item ) ) {
569 $class = $item['class'];
570 } elseif ( array_key_exists( 'type', $item ) ) {
571 $class = HTMLForm::$typeMappings[$item['type']];
573 return !is_a( $class, \HTMLInfoField::class, true ) &&
574 !is_a( $class, \HTMLSubmitField::class, true );
575 } );
579 * Adds a sequential tabindex starting from 1 to all form elements. This way the user can
580 * use the tab key to traverse the form without having to step through all links and such.
581 * @param $formDescriptor
583 protected function addTabIndex( &$formDescriptor ) {
584 $i = 1;
585 foreach ( $formDescriptor as $field => &$definition ) {
586 $class = false;
587 if ( array_key_exists( 'class', $definition ) ) {
588 $class = $definition['class'];
589 } elseif ( array_key_exists( 'type', $definition ) ) {
590 $class = HTMLForm::$typeMappings[$definition['type']];
592 if ( $class !== 'HTMLInfoField' ) {
593 $definition['tabindex'] = $i;
594 $i++;
600 * Returns the CSRF token.
601 * @return Token
603 protected function getToken() {
604 return $this->getRequest()->getSession()->getToken( 'AuthManagerSpecialPage:'
605 . $this->getName() );
609 * Returns the name of the CSRF token (under which it should be found in the POST or GET data).
610 * @return string
612 protected function getTokenName() {
613 return 'wpAuthToken';
617 * Turns a field info array into a form descriptor. Behavior can be modified by the
618 * AuthChangeFormFields hook.
619 * @param AuthenticationRequest[] $requests
620 * @param array $fieldInfo Field information, in the format used by
621 * AuthenticationRequest::getFieldInfo()
622 * @param string $action One of the AuthManager::ACTION_* constants
623 * @return array A form descriptor that can be passed to HTMLForm
625 protected function fieldInfoToFormDescriptor( array $requests, array $fieldInfo, $action ) {
626 $formDescriptor = [];
627 foreach ( $fieldInfo as $fieldName => $singleFieldInfo ) {
628 $formDescriptor[$fieldName] = self::mapSingleFieldInfo( $singleFieldInfo, $fieldName );
631 $requestSnapshot = serialize( $requests );
632 $this->onAuthChangeFormFields( $requests, $fieldInfo, $formDescriptor, $action );
633 \Hooks::run( 'AuthChangeFormFields', [ $requests, $fieldInfo, &$formDescriptor, $action ] );
634 if ( $requestSnapshot !== serialize( $requests ) ) {
635 LoggerFactory::getInstance( 'authentication' )->warning(
636 'AuthChangeFormFields hook changed auth requests' );
639 // Process the special 'weight' property, which is a way for AuthChangeFormFields hook
640 // subscribers (who only see one field at a time) to influence ordering.
641 self::sortFormDescriptorFields( $formDescriptor );
643 return $formDescriptor;
647 * Maps an authentication field configuration for a single field (as returned by
648 * AuthenticationRequest::getFieldInfo()) to a HTMLForm field descriptor.
649 * @param array $singleFieldInfo
650 * @return array
652 protected static function mapSingleFieldInfo( $singleFieldInfo, $fieldName ) {
653 $type = self::mapFieldInfoTypeToFormDescriptorType( $singleFieldInfo['type'] );
654 $descriptor = [
655 'type' => $type,
656 // Do not prefix input name with 'wp'. This is important for the redirect flow.
657 'name' => $fieldName,
660 if ( $type === 'submit' && isset( $singleFieldInfo['label'] ) ) {
661 $descriptor['default'] = wfMessage( $singleFieldInfo['label'] )->plain();
662 } elseif ( $type !== 'submit' ) {
663 $descriptor += array_filter( [
664 // help-message is omitted as it is usually not really useful for a web interface
665 'label-message' => self::getField( $singleFieldInfo, 'label' ),
666 ] );
668 if ( isset( $singleFieldInfo['options'] ) ) {
669 $descriptor['options'] = array_flip( array_map( function ( $message ) {
670 /** @var $message Message */
671 return $message->parse();
672 }, $singleFieldInfo['options'] ) );
675 if ( isset( $singleFieldInfo['value'] ) ) {
676 $descriptor['default'] = $singleFieldInfo['value'];
679 if ( empty( $singleFieldInfo['optional'] ) ) {
680 $descriptor['required'] = true;
684 return $descriptor;
688 * Sort the fields of a form descriptor by their 'weight' property. (Fields with higher weight
689 * are shown closer to the bottom; weight defaults to 0. Negative weight is allowed.)
690 * Keep order if weights are equal.
691 * @param array $formDescriptor
692 * @return array
694 protected static function sortFormDescriptorFields( array &$formDescriptor ) {
695 $i = 0;
696 foreach ( $formDescriptor as &$field ) {
697 $field['__index'] = $i++;
699 uasort( $formDescriptor, function ( $first, $second ) {
700 return self::getField( $first, 'weight', 0 ) - self::getField( $second, 'weight', 0 )
701 ?: $first['__index'] - $second['__index'];
702 } );
703 foreach ( $formDescriptor as &$field ) {
704 unset( $field['__index'] );
709 * Get an array value, or a default if it does not exist.
710 * @param array $array
711 * @param string $fieldName
712 * @param mixed $default
713 * @return mixed
715 protected static function getField( array $array, $fieldName, $default = null ) {
716 if ( array_key_exists( $fieldName, $array ) ) {
717 return $array[$fieldName];
718 } else {
719 return $default;
724 * Maps AuthenticationRequest::getFieldInfo() types to HTMLForm types
725 * @param string $type
726 * @return string
727 * @throws \LogicException
729 protected static function mapFieldInfoTypeToFormDescriptorType( $type ) {
730 $map = [
731 'string' => 'text',
732 'password' => 'password',
733 'select' => 'select',
734 'checkbox' => 'check',
735 'multiselect' => 'multiselect',
736 'button' => 'submit',
737 'hidden' => 'hidden',
738 'null' => 'info',
740 if ( !array_key_exists( $type, $map ) ) {
741 throw new \LogicException( 'invalid field type: ' . $type );
743 return $map[$type];