Use AuthManager on special pages
[lhc/web/wiklou.git] / includes / specialpage / AuthManagerSpecialPage.php
1 <?php
2
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;
9
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.
14 */
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,
23 ];
24
25 /** @var array Customized messages */
26 protected static $messages = [];
27
28 /** @var string one of the AuthManager::ACTION_* constants. */
29 protected $authAction;
30
31 /** @var AuthenticationRequest[] */
32 protected $authRequests;
33
34 /** @var string Subpage of the special page. */
35 protected $subPage;
36
37 /** @var bool True if the current request is a result of returning from a redirect flow. */
38 protected $isReturn;
39
40 /** @var WebRequest|null If set, will be used instead of the real request. Used for redirection. */
41 protected $savedRequest;
42
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
53 */
54 public function onAuthChangeFormFields(
55 array $requests, array $fieldInfo, array &$formDescriptor, $action
56 ) {
57 return true;
58 }
59
60 protected function getLoginSecurityLevel() {
61 return $this->getName();
62 }
63
64 public function getRequest() {
65 return $this->savedRequest ?: $this->getContext()->getRequest();
66 }
67
68 /**
69 * Override the POST data, GET data from the real request is preserved.
70 *
71 * Used to preserve POST data over a HTTP redirect.
72 *
73 * @param array $data
74 * @param bool $wasPosted
75 */
76 protected function setRequest( array $data, $wasPosted = null ) {
77 $request = $this->getContext()->getRequest();
78 if ( $wasPosted === null ) {
79 $wasPosted = $request->wasPosted();
80 }
81 $this->savedRequest = new DerivativeRequest( $request, $data + $request->getQueryValues(),
82 $wasPosted );
83 }
84
85 protected function beforeExecute( $subPage ) {
86 $this->getOutput()->disallowUserJs();
87
88 return $this->handleReturnBeforeExecute( $subPage )
89 && $this->handleReauthBeforeExecute( $subPage );
90 }
91
92 /**
93 * Handle redirection from the /return subpage.
94 *
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.)
100 *
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.
104 *
105 * @param string $subPage
106 * @return bool False if execution should be stopped.
107 */
108 protected function handleReturnBeforeExecute( $subPage ) {
109 $authManager = AuthManager::singleton();
110 $key = 'AuthManagerSpecialPage:return:' . $this->getName();
111
112 if ( $subPage === 'return' ) {
113 $this->loadAuth( $subPage );
114 $preservedParams = $this->getPreservedParams( false );
115
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 );
120
121 $url = $this->getPageTitle()->getFullURL( $preservedParams, false, PROTO_HTTPS );
122 $this->getOutput()->redirect( $url );
123 return false;
124 }
125
126 $authData = $authManager->getAuthenticationSessionData( $key );
127 if ( $authData ) {
128 $authManager->removeAuthenticationSessionData( $key );
129 $this->isReturn = true;
130 $this->setRequest( $authData, true );
131 }
132
133 return true;
134 }
135
136 /**
137 * Handle redirection when the user needs to (re)authenticate.
138 *
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.
141 *
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.
145 */
146 protected function handleReauthBeforeExecute( $subPage ) {
147 $authManager = AuthManager::singleton();
148 $request = $this->getRequest();
149 $key = 'AuthManagerSpecialPage:reauth:' . $this->getName();
150
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 ] );
157
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;
162
163 $queryParams = [ 'authUniqueId' => $uniqueId ] + $queryParams;
164 $authData = array_diff_key( $request->getValues(),
165 $this->getPreservedParams( false ), [ 'title' => 1 ] );
166 $authManager->setAuthenticationSessionData( $key, $authData );
167 }
168
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 );
175
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' );
180 }
181 }
182
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 );
190 }
191 }
192
193 return true;
194 }
195
196 /**
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.
201 */
202 protected function getDefaultAction( $subPage ) {
203 throw new BadMethodCallException( 'Subclass did not implement getDefaultAction' );
204 }
205
206 /**
207 * Return custom message key.
208 * Allows subclasses to customize messages.
209 * @return string
210 */
211 protected function messageKey( $defaultKey ) {
212 return array_key_exists( $defaultKey, static::$messages )
213 ? static::$messages[$defaultKey] : $defaultKey;
214 }
215
216 /**
217 * Allows blacklisting certain request types.
218 * @return array A list of AuthenticationRequest subclass names
219 */
220 protected function getRequestBlacklist() {
221 return [];
222 }
223
224 /**
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
232 */
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 )
240 ) {
241 return;
242 }
243
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;
253 }
254 }
255 }
256
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 } );
262 }
263
264 /**
265 * Returns true if this is not the first step of the authentication.
266 * @return bool
267 */
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 );
274 }
275
276 /**
277 * Gets the _CONTINUE version of an action.
278 * @param string $action An AuthManager::ACTION_* constant.
279 * @return string An AuthManager::ACTION_*_CONTINUE constant.
280 */
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;
292 }
293 return $action;
294 }
295
296 /**
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
303 */
304 protected function isActionAllowed( $action ) {
305 $authManager = AuthManager::singleton();
306 if ( !in_array( $action, static::$allowedActions, true ) ) {
307 throw new InvalidArgumentException( 'invalid action: ' . $action );
308 }
309
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;
316 }
317
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 );
335 }
336 }
337
338 /**
339 * @param string $action One of the AuthManager::ACTION_* constants
340 * @param AuthenticationRequest[] $requests
341 * @return AuthenticationResponse
342 * @throws LogicException if $action is invalid
343 */
344 protected function performAuthenticationStep( $action, array $requests ) {
345 if ( !in_array( $action, static::$allowedActions, true ) ) {
346 throw new InvalidArgumentException( 'invalid action: ' . $action );
347 }
348
349 $authManager = AuthManager::singleton();
350 $returnToUrl = $this->getPageTitle( 'return' )
351 ->getFullURL( $this->getPreservedParams( true ), false, PROTO_HTTPS );
352
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' );
374 }
375 $req = reset( $requests );
376 $status = $authManager->allowsAuthenticationDataChange( $req );
377 Hooks::run( 'ChangeAuthenticationDataAudit', [ $req, $status ] );
378 if ( !$status->isOK() ) {
379 return AuthenticationResponse::newFail( $status->getMessage() );
380 }
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 );
386 }
387 }
388
389 /**
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.
398 */
399 protected function trySubmit() {
400 $status = false;
401
402 $form = $this->getAuthForm( $this->authRequests, $this->authAction );
403 $form->setSubmitCallback( [ $this, 'handleFormSubmit' ] );
404
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' ) );
415 }
416
417 $form->prepareForm();
418 $status = $form->trySubmit();
419
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 );
442 }
443 } else {
444 throw new UnexpectedValueException( 'invalid HTMLForm::trySubmit() return value: '
445 . 'first element of array is ' . gettype( reset( $status ) ) );
446 }
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 ) );
452 }
453
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 );
463 }
464 }
465
466 $changeActions = [
467 AuthManager::ACTION_CHANGE, AuthManager::ACTION_REMOVE, AuthManager::ACTION_UNLINK
468 ];
469 if ( in_array( $this->authAction, $changeActions, true ) && $status && !$status->isOK() ) {
470 Hooks::run( 'ChangeAuthenticationDataAudit', [ reset( $this->authRequests ), $status ] );
471 }
472
473 return $status;
474 }
475
476 /**
477 * Submit handler callback for HTMLForm
478 * @private
479 * @param $data array Submitted data
480 * @return Status
481 */
482 public function handleFormSubmit( $data ) {
483 $requests = AuthenticationRequest::loadRequestsFromSubmission( $this->authRequests, $data );
484 $response = $this->performAuthenticationStep( $this->authAction, $requests );
485
486 // we can't handle FAIL or similar as failure here since it might require changing the form
487 return Status::newGood( $response );
488 }
489
490 /**
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
496 */
497 protected function getPreservedParams( $withToken = false ) {
498 $params = [];
499 if ( $this->authAction !== $this->getDefaultAction( $this->subPage ) ) {
500 $params['authAction'] = $this->getContinueAction( $this->authAction );
501 }
502 if ( $withToken ) {
503 $params[$this->getTokenName()] = $this->getToken()->toString();
504 }
505 return $params;
506 }
507
508 /**
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
513 */
514 protected function getAuthFormDescriptor( $requests, $action ) {
515 $fieldInfo = AuthenticationRequest::mergeFieldInfo( $requests );
516 $formDescriptor = $this->fieldInfoToFormDescriptor( $requests, $fieldInfo, $action );
517
518 $this->addTabIndex( $formDescriptor );
519
520 return $formDescriptor;
521 }
522
523 /**
524 * @param AuthenticationRequest[] $requests
525 * @param string $action AuthManager action name (one of the AuthManager::ACTION_* constants)
526 * @return HTMLForm
527 */
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() );
535 }
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 ) );
541
542 return $form;
543 }
544
545 /**
546 * Display the form.
547 * @param false|Status|StatusValue $status A form submit status, as in HTMLForm::trySubmit()
548 */
549 protected function displayForm( $status ) {
550 if ( $status instanceof StatusValue ) {
551 $status = Status::wrap( $status );
552 }
553 $form = $this->getAuthForm( $this->authRequests, $this->authAction );
554 $form->prepareForm()->displayForm( $status );
555 }
556
557 /**
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.
561 *
562 * @param array $formDescriptor A HTMLForm descriptor
563 * @return bool
564 */
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']];
572 }
573 return !in_array( $class, [ 'HTMLInfoField', 'HTMLSubmitField' ], true );
574 } );
575 }
576
577 /**
578 * Adds a sequential tabindex starting from 1 to all form elements. This way the user can
579 * use the tab key to traverse the form without having to step through all links and such.
580 * @param $formDescriptor
581 */
582 protected function addTabIndex( &$formDescriptor ) {
583 $i = 1;
584 foreach ( $formDescriptor as $field => &$definition ) {
585 $class = false;
586 if ( array_key_exists( 'class', $definition ) ) {
587 $class = $definition['class'];
588 } elseif ( array_key_exists( 'type', $definition ) ) {
589 $class = HTMLForm::$typeMappings[$definition['type']];
590 }
591 if ( $class !== 'HTMLInfoField' ) {
592 $definition['tabindex'] = $i;
593 $i++;
594 }
595 }
596 }
597
598 /**
599 * Returns the CSRF token.
600 * @return Token
601 */
602 protected function getToken() {
603 return $this->getRequest()->getSession()->getToken( 'AuthManagerSpecialPage:'
604 . $this->getName() );
605 }
606
607 /**
608 * Returns the name of the CSRF token (under which it should be found in the POST or GET data).
609 * @return string
610 */
611 protected function getTokenName() {
612 return 'wpAuthToken';
613 }
614
615 /**
616 * Turns a field info array into a form descriptor. Behavior can be modified by the
617 * AuthChangeFormFields hook.
618 * @param AuthenticationRequest[] $requests
619 * @param array $fieldInfo Field information, in the format used by
620 * AuthenticationRequest::getFieldInfo()
621 * @param string $action One of the AuthManager::ACTION_* constants
622 * @return array A form descriptor that can be passed to HTMLForm
623 */
624 protected function fieldInfoToFormDescriptor( array $requests, array $fieldInfo, $action ) {
625 $formDescriptor = [];
626 foreach ( $fieldInfo as $fieldName => $singleFieldInfo ) {
627 $formDescriptor[$fieldName] = self::mapSingleFieldInfo( $singleFieldInfo, $fieldName );
628 }
629
630 $requestSnapshot = serialize( $requests );
631 $this->onAuthChangeFormFields( $requests, $fieldInfo, $formDescriptor, $action );
632 \Hooks::run( 'AuthChangeFormFields', [ $requests, $fieldInfo, &$formDescriptor, $action ] );
633 if ( $requestSnapshot !== serialize( $requests ) ) {
634 LoggerFactory::getInstance( 'authentication' )->warning(
635 'AuthChangeFormFields hook changed auth requests' );
636 }
637
638 // Process the special 'weight' property, which is a way for AuthChangeFormFields hook
639 // subscribers (who only see one field at a time) to influence ordering.
640 self::sortFormDescriptorFields( $formDescriptor );
641
642 return $formDescriptor;
643 }
644
645 /**
646 * Maps an authentication field configuration for a single field (as returned by
647 * AuthenticationRequest::getFieldInfo()) to a HTMLForm field descriptor.
648 * @param array $singleFieldInfo
649 * @return array
650 */
651 protected static function mapSingleFieldInfo( $singleFieldInfo, $fieldName ) {
652 $type = self::mapFieldInfoTypeToFormDescriptorType( $singleFieldInfo['type'] );
653 $descriptor = [
654 'type' => $type,
655 // Do not prefix input name with 'wp'. This is important for the redirect flow.
656 'name' => $fieldName,
657 ];
658
659 if ( $type === 'submit' && isset( $singleFieldInfo['label'] ) ) {
660 $descriptor['default'] = wfMessage( $singleFieldInfo['label'] )->plain();
661 } elseif ( $type !== 'submit' ) {
662 $descriptor += array_filter( [
663 // help-message is omitted as it is usually not really useful for a web interface
664 'label-message' => self::getField( $singleFieldInfo, 'label' ),
665 ] );
666
667 if ( isset( $singleFieldInfo['options'] ) ) {
668 $descriptor['options'] = array_flip( array_map( function ( $message ) {
669 /** @var $message Message */
670 return $message->parse();
671 }, $singleFieldInfo['options'] ) );
672 }
673
674 if ( isset( $singleFieldInfo['value'] ) ) {
675 $descriptor['default'] = $singleFieldInfo['value'];
676 }
677
678 if ( empty( $singleFieldInfo['optional'] ) ) {
679 $descriptor['required'] = true;
680 }
681 }
682
683 return $descriptor;
684 }
685
686 /**
687 * Sort the fields of a form descriptor by their 'weight' property. (Fields with higher weight
688 * are shown closer to the bottom; weight defaults to 0. Negative weight is allowed.)
689 * Keep order if weights are equal.
690 * @param array $formDescriptor
691 * @return array
692 */
693 protected static function sortFormDescriptorFields( array &$formDescriptor ) {
694 $i = 0;
695 foreach ( $formDescriptor as &$field ) {
696 $field['__index'] = $i++;
697 }
698 uasort( $formDescriptor, function ( $first, $second ) {
699 return self::getField( $first, 'weight', 0 ) - self::getField( $second, 'weight', 0 )
700 ?: $first['__index'] - $second['__index'];
701 } );
702 foreach ( $formDescriptor as &$field ) {
703 unset( $field['__index'] );
704 }
705 }
706
707 /**
708 * Get an array value, or a default if it does not exist.
709 * @param array $array
710 * @param string $fieldName
711 * @param mixed $default
712 * @return mixed
713 */
714 protected static function getField( array $array, $fieldName, $default = null ) {
715 if ( array_key_exists( $fieldName, $array ) ) {
716 return $array[$fieldName];
717 } else {
718 return $default;
719 }
720 }
721
722 /**
723 * Maps AuthenticationRequest::getFieldInfo() types to HTMLForm types
724 * @param string $type
725 * @return string
726 * @throws \LogicException
727 */
728 protected static function mapFieldInfoTypeToFormDescriptorType( $type ) {
729 $map = [
730 'string' => 'text',
731 'password' => 'password',
732 'select' => 'select',
733 'checkbox' => 'check',
734 'multiselect' => 'multiselect',
735 'button' => 'submit',
736 'hidden' => 'hidden',
737 'null' => 'info',
738 ];
739 if ( !array_key_exists( $type, $map ) ) {
740 throw new \LogicException( 'invalid field type: ' . $type );
741 }
742 return $map[$type];
743 }
744 }