MediaWiki  master
AuthManagerSpecialPage.php
Go to the documentation of this file.
1 <?php
2 
8 
14 abstract class AuthManagerSpecialPage extends SpecialPage {
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 
26  protected static $messages = [];
27 
29  protected $authAction;
30 
32  protected $authRequests;
33 
35  protected $subPage;
36 
38  protected $isReturn;
39 
41  protected $savedRequest;
42 
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 
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 )
90  }
91 
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 
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 .= ':' . $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 .= ':' . $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 
202  abstract protected function getDefaultAction( $subPage );
203 
210  protected function messageKey( $defaultKey ) {
211  return array_key_exists( $defaultKey, static::$messages )
212  ? static::$messages[$defaultKey] : $defaultKey;
213  }
214 
219  protected function getRequestBlacklist() {
220  return [];
221  }
222 
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.
236  if (
237  !$reset && $this->subPage === $subPage && $this->authAction
238  && ( !$authAction || $authAction === $this->authAction )
239  ) {
240  return;
241  }
242 
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;
252  }
253  }
254  }
255 
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 );
260  } );
261  }
262 
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,
272  ], true );
273  }
274 
280  protected function getContinueAction( $action ) {
281  switch ( $action ) {
282  case AuthManager::ACTION_LOGIN:
283  $action = AuthManager::ACTION_LOGIN_CONTINUE;
284  break;
285  case AuthManager::ACTION_CREATE:
286  $action = AuthManager::ACTION_CREATE_CONTINUE;
287  break;
288  case AuthManager::ACTION_LINK:
289  $action = AuthManager::ACTION_LINK_CONTINUE;
290  break;
291  }
292  return $action;
293  }
294 
303  protected function isActionAllowed( $action ) {
304  $authManager = AuthManager::singleton();
305  if ( !in_array( $action, static::$allowedActions, true ) ) {
306  throw new InvalidArgumentException( 'invalid action: ' . $action );
307  }
308 
309  // calling getAuthenticationRequests can be expensive, avoid if possible
310  $requests = ( $action === $this->authAction ) ? $this->authRequests
311  : $authManager->getAuthenticationRequests( $action );
312  if ( !$requests ) {
313  // no provider supports this action in the current state
314  return false;
315  }
316 
317  switch ( $action ) {
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:
330  return true;
331  default:
332  // should never reach here but makes static code analyzers happy
333  throw new InvalidArgumentException( 'invalid action: ' . $action );
334  }
335  }
336 
343  protected function performAuthenticationStep( $action, array $requests ) {
344  if ( !in_array( $action, static::$allowedActions, true ) ) {
345  throw new InvalidArgumentException( 'invalid action: ' . $action );
346  }
347 
348  $authManager = AuthManager::singleton();
349  $returnToUrl = $this->getPageTitle( 'return' )
350  ->getFullURL( $this->getPreservedParams( true ), false, PROTO_HTTPS );
351 
352  switch ( $action ) {
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,
359  $returnToUrl );
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' );
373  }
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() );
379  }
380  $authManager->changeAuthenticationData( $req );
381  return AuthenticationResponse::newPass();
382  default:
383  // should never reach here but makes static code analyzers happy
384  throw new InvalidArgumentException( 'invalid action: ' . $action );
385  }
386  }
387 
398  protected function trySubmit() {
399  $status = false;
400 
401  $form = $this->getAuthForm( $this->authRequests, $this->authAction );
402  $form->setSubmitCallback( [ $this, 'handleFormSubmit' ] );
403 
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' ) );
414  }
415 
416  $form->prepareForm();
417  $status = $form->trySubmit();
418 
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
432  } elseif ( is_string( $status ) ) {
433  $status = Status::newFatal( new RawMessage( '$1', [ $status ] ) );
434  } elseif ( is_array( $status ) ) {
435  if ( is_string( reset( $status ) ) ) {
437  } elseif ( is_array( reset( $status ) ) ) {
439  foreach ( $status as $message ) {
440  $status->fatal( ...$message );
441  }
442  } else {
443  throw new UnexpectedValueException( 'invalid HTMLForm::trySubmit() return value: '
444  . 'first element of array is ' . gettype( reset( $status ) ) );
445  }
446  } else {
447  // not supposed to happen but HTMLForm does not actually verify the return type
448  // from the submit callback; better safe then sorry
449  throw new UnexpectedValueException( 'invalid HTMLForm::trySubmit() return type: '
450  . gettype( $status ) );
451  }
452 
453  if ( ( !$status || !$status->isOK() ) && $this->isReturn ) {
454  // This is awkward. There was a form validation error, which means the data was not
455  // passed to AuthManager. Normally we would display the form with an error message,
456  // but for the data we received via the redirect flow that would not be helpful at all.
457  // Let's just submit the data to AuthManager directly instead.
458  LoggerFactory::getInstance( 'authentication' )
459  ->warning( 'Validation error on return', [ 'data' => $form->mFieldData,
460  'status' => $status->getWikiText( false, false, 'en' ) ] );
461  $status = $this->handleFormSubmit( $form->mFieldData );
462  }
463  }
464 
465  $changeActions = [
466  AuthManager::ACTION_CHANGE, AuthManager::ACTION_REMOVE, AuthManager::ACTION_UNLINK
467  ];
468  if ( in_array( $this->authAction, $changeActions, true ) && $status && !$status->isOK() ) {
469  Hooks::run( 'ChangeAuthenticationDataAudit', [ reset( $this->authRequests ), $status ] );
470  }
471 
472  return $status;
473  }
474 
481  public function handleFormSubmit( $data ) {
482  $requests = AuthenticationRequest::loadRequestsFromSubmission( $this->authRequests, $data );
483  $response = $this->performAuthenticationStep( $this->authAction, $requests );
484 
485  // we can't handle FAIL or similar as failure here since it might require changing the form
486  return Status::newGood( $response );
487  }
488 
496  protected function getPreservedParams( $withToken = false ) {
497  $params = [];
498  if ( $this->authAction !== $this->getDefaultAction( $this->subPage ) ) {
499  $params['authAction'] = $this->getContinueAction( $this->authAction );
500  }
501  if ( $withToken ) {
502  $params[$this->getTokenName()] = $this->getToken()->toString();
503  }
504  return $params;
505  }
506 
513  protected function getAuthFormDescriptor( $requests, $action ) {
514  $fieldInfo = AuthenticationRequest::mergeFieldInfo( $requests );
515  $formDescriptor = $this->fieldInfoToFormDescriptor( $requests, $fieldInfo, $action );
516 
517  $this->addTabIndex( $formDescriptor );
518 
519  return $formDescriptor;
520  }
521 
527  protected function getAuthForm( array $requests, $action ) {
528  $formDescriptor = $this->getAuthFormDescriptor( $requests, $action );
529  $context = $this->getContext();
530  if ( $context->getRequest() !== $this->getRequest() ) {
531  // We have overridden the request, need to make sure the form uses that too.
532  $context = new DerivativeContext( $this->getContext() );
533  $context->setRequest( $this->getRequest() );
534  }
535  $form = HTMLForm::factory( 'ooui', $formDescriptor, $context );
536  $form->setAction( $this->getFullTitle()->getFullURL( $this->getPreservedParams() ) );
537  $form->addHiddenField( $this->getTokenName(), $this->getToken()->toString() );
538  $form->addHiddenField( 'authAction', $this->authAction );
539  $form->suppressDefaultSubmit( !$this->needsSubmitButton( $requests ) );
540 
541  return $form;
542  }
543 
548  protected function displayForm( $status ) {
549  if ( $status instanceof StatusValue ) {
551  }
552  $form = $this->getAuthForm( $this->authRequests, $this->authAction );
553  $form->prepareForm()->displayForm( $status );
554  }
555 
566  protected function needsSubmitButton( array $requests ) {
567  $customSubmitButtonPresent = false;
568 
569  // Secondary and preauth providers always need their data; they will not care what button
570  // is used, so they can be ignored. So can OPTIONAL buttons createdby primary providers;
571  // that's the point in being optional. Se we need to check whether all primary providers
572  // have their own buttons and whether there is at least one button present.
573  foreach ( $requests as $req ) {
574  if ( $req->required === AuthenticationRequest::PRIMARY_REQUIRED ) {
575  if ( $this->hasOwnSubmitButton( $req ) ) {
576  $customSubmitButtonPresent = true;
577  } else {
578  return true;
579  }
580  }
581  }
582  return !$customSubmitButtonPresent;
583  }
584 
591  foreach ( $req->getFieldInfo() as $field => $info ) {
592  if ( $info['type'] === 'button' ) {
593  return true;
594  }
595  }
596  return false;
597  }
598 
604  protected function addTabIndex( &$formDescriptor ) {
605  $i = 1;
606  foreach ( $formDescriptor as $field => &$definition ) {
607  $class = false;
608  if ( array_key_exists( 'class', $definition ) ) {
609  $class = $definition['class'];
610  } elseif ( array_key_exists( 'type', $definition ) ) {
611  $class = HTMLForm::$typeMappings[$definition['type']];
612  }
613  if ( $class !== HTMLInfoField::class ) {
614  $definition['tabindex'] = $i;
615  $i++;
616  }
617  }
618  }
619 
624  protected function getToken() {
625  return $this->getRequest()->getSession()->getToken( 'AuthManagerSpecialPage:'
626  . $this->getName() );
627  }
628 
633  protected function getTokenName() {
634  return 'wpAuthToken';
635  }
636 
646  protected function fieldInfoToFormDescriptor( array $requests, array $fieldInfo, $action ) {
647  $formDescriptor = [];
648  foreach ( $fieldInfo as $fieldName => $singleFieldInfo ) {
649  $formDescriptor[$fieldName] = self::mapSingleFieldInfo( $singleFieldInfo, $fieldName );
650  }
651 
652  $requestSnapshot = serialize( $requests );
653  $this->onAuthChangeFormFields( $requests, $fieldInfo, $formDescriptor, $action );
654  \Hooks::run( 'AuthChangeFormFields', [ $requests, $fieldInfo, &$formDescriptor, $action ] );
655  if ( $requestSnapshot !== serialize( $requests ) ) {
656  LoggerFactory::getInstance( 'authentication' )->warning(
657  'AuthChangeFormFields hook changed auth requests' );
658  }
659 
660  // Process the special 'weight' property, which is a way for AuthChangeFormFields hook
661  // subscribers (who only see one field at a time) to influence ordering.
662  self::sortFormDescriptorFields( $formDescriptor );
663 
664  return $formDescriptor;
665  }
666 
674  protected static function mapSingleFieldInfo( $singleFieldInfo, $fieldName ) {
675  $type = self::mapFieldInfoTypeToFormDescriptorType( $singleFieldInfo['type'] );
676  $descriptor = [
677  'type' => $type,
678  // Do not prefix input name with 'wp'. This is important for the redirect flow.
679  'name' => $fieldName,
680  ];
681 
682  if ( $type === 'submit' && isset( $singleFieldInfo['label'] ) ) {
683  $descriptor['default'] = $singleFieldInfo['label']->plain();
684  } elseif ( $type !== 'submit' ) {
685  $descriptor += array_filter( [
686  // help-message is omitted as it is usually not really useful for a web interface
687  'label-message' => self::getField( $singleFieldInfo, 'label' ),
688  ] );
689 
690  if ( isset( $singleFieldInfo['options'] ) ) {
691  $descriptor['options'] = array_flip( array_map( function ( $message ) {
693  return $message->parse();
694  }, $singleFieldInfo['options'] ) );
695  }
696 
697  if ( isset( $singleFieldInfo['value'] ) ) {
698  $descriptor['default'] = $singleFieldInfo['value'];
699  }
700 
701  if ( empty( $singleFieldInfo['optional'] ) ) {
702  $descriptor['required'] = true;
703  }
704  }
705 
706  return $descriptor;
707  }
708 
715  protected static function sortFormDescriptorFields( array &$formDescriptor ) {
716  $i = 0;
717  foreach ( $formDescriptor as &$field ) {
718  $field['__index'] = $i++;
719  }
720  uasort( $formDescriptor, function ( $first, $second ) {
721  return self::getField( $first, 'weight', 0 ) <=> self::getField( $second, 'weight', 0 )
722  ?: $first['__index'] <=> $second['__index'];
723  } );
724  foreach ( $formDescriptor as &$field ) {
725  unset( $field['__index'] );
726  }
727  }
728 
736  protected static function getField( array $array, $fieldName, $default = null ) {
737  if ( array_key_exists( $fieldName, $array ) ) {
738  return $array[$fieldName];
739  } else {
740  return $default;
741  }
742  }
743 
750  protected static function mapFieldInfoTypeToFormDescriptorType( $type ) {
751  $map = [
752  'string' => 'text',
753  'password' => 'password',
754  'select' => 'select',
755  'checkbox' => 'check',
756  'multiselect' => 'multiselect',
757  'button' => 'submit',
758  'hidden' => 'hidden',
759  'null' => 'info',
760  ];
761  if ( !array_key_exists( $type, $map ) ) {
762  throw new \LogicException( 'invalid field type: ' . $type );
763  }
764  return $map[$type];
765  }
766 }
loadAuth( $subPage, $authAction=null, $reset=false)
Load or initialize $authAction, $authRequests and $subPage.
static array $messages
Customized messages.
static $typeMappings
Definition: HTMLForm.php:133
hasOwnSubmitButton(AuthenticationRequest $req)
Checks whether the given AuthenticationRequest has its own submit button.
A special page subclass for authentication-related special pages.
getContext()
Gets the context this SpecialPage is executed in.
serialize()
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
needsSubmitButton(array $requests)
Returns true if the form built from the given AuthenticationRequests needs a submit button...
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead & $formDescriptor
Definition: hooks.txt:2051
static string [] $allowedActions
The list of actions this special page deals with.
An IContextSource implementation which will inherit context from another source but allow individual ...
Similar to FauxRequest, but only fakes URL parameters and method (POST or GET) and use the base reque...
getFieldInfo()
Fetch input field info.
getToken()
Returns the CSRF token.
getOutput()
Get the OutputPage being used for this instance.
this hook is for auditing only $response
Definition: hooks.txt:767
static factory( $displayFormat)
Construct a HTMLForm object for given display type.
Definition: HTMLForm.php:299
static mapSingleFieldInfo( $singleFieldInfo, $fieldName)
Maps an authentication field configuration for a single field (as returned by AuthenticationRequest::...
getRequestBlacklist()
Allows blacklisting certain request types.
setRequest(array $data, $wasPosted=null)
Override the POST data, GET data from the real request is preserved.
wfArrayToCgi( $array1, $array2=null, $prefix='')
This function takes one or two arrays as input, and returns a CGI-style string, e.g.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1972
getContinueAction( $action)
Gets the _CONTINUE version of an action.
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:68
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition: hooks.txt:1244
getDefaultAction( $subPage)
Get the default action for this special page, if none is given via URL/POST data. ...
bool $isReturn
True if the current request is a result of returning from a redirect flow.
const PROTO_HTTPS
Definition: Defines.php:200
isContinued()
Returns true if this is not the first step of the authentication.
isActionAllowed( $action)
Checks whether AuthManager is ready to perform the action.
addTabIndex(&$formDescriptor)
Adds a sequential tabindex starting from 1 to all form elements.
An error page which can definitely be safely rendered using the OutputPage.
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
handleReauthBeforeExecute( $subPage)
Handle redirection when the user needs to (re)authenticate.
$params
static generateHex( $chars)
Generate a run of cryptographically random data and return it in hexadecimal string format...
Definition: MWCryptRand.php:36
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:767
Allows to change the fields on the form that will be generated are created Can be used to omit specific feeds from being outputted You must not use this hook to add use OutputPage::addFeedLink() instead. & $feedLinks hooks can tweak the array to change how login etc forms should look $requests
Definition: hooks.txt:273
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don&#39;t need a full Title object...
Definition: SpecialPage.php:83
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
WebRequest null $savedRequest
If set, will be used instead of the real request.
static wrap( $sv)
Succinct helper method to wrap a StatusValue.
Definition: Status.php:55
onAuthChangeFormFields(array $requests, array $fieldInfo, array &$formDescriptor, $action)
Change the form descriptor that determines how a field will look in the authentication form...
AuthenticationRequest [] $authRequests
static getField(array $array, $fieldName, $default=null)
Get an array value, or a default if it does not exist.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
this hook is for auditing only $req
Definition: hooks.txt:960
displayForm( $status)
Display the form.
getTokenName()
Returns the name of the CSRF token (under which it should be found in the POST or GET data)...
getName()
Get the name of this Special Page.
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
getAuthFormDescriptor( $requests, $action)
Generates a HTMLForm descriptor array from a set of authentication requests.
Variant of the Message class.
Definition: RawMessage.php:34
getUser()
Shortcut to get the User executing this instance.
static sortFormDescriptorFields(array &$formDescriptor)
Sort the fields of a form descriptor by their &#39;weight&#39; property.
fieldInfoToFormDescriptor(array $requests, array $fieldInfo, $action)
Turns a field info array into a form descriptor.
handleFormSubmit( $data)
Submit handler callback for HTMLForm.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2621
getAuthForm(array $requests, $action)
MediaWiki Logger LoggerFactory implements a PSR [0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
performAuthenticationStep( $action, array $requests)
getFullTitle()
Return the full title, including $par.
$messages
messageKey( $defaultKey)
Return custom message key.
string $subPage
Subpage of the special page.
static mapFieldInfoTypeToFormDescriptorType( $type)
Maps AuthenticationRequest::getFieldInfo() types to HTMLForm types.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2621
getPageTitle( $subpage=false)
Get a self-referential title object.
getPreservedParams( $withToken=false)
Returns URL query parameters which can be used to reload the page (or leave and return) while preserv...
handleReturnBeforeExecute( $subPage)
Handle redirection from the /return subpage.
This is a value object for authentication requests.
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
string $authAction
one of the AuthManager::ACTION_* constants.
trySubmit()
Attempts to do an authentication step with the submitted data.