MediaWiki  1.27.1
ApiAuthManagerHelper.php
Go to the documentation of this file.
1 <?php
28 
36 
38  private $module;
39 
41  private $messageFormat;
42 
46  public function __construct( ApiBase $module ) {
47  $this->module = $module;
48 
49  $params = $module->extractRequestParams();
50  $this->messageFormat = isset( $params['messageformat'] ) ? $params['messageformat'] : 'wikitext';
51  }
52 
58  public static function newForModule( ApiBase $module ) {
59  return new self( $module );
60  }
61 
68  private function formatMessage( array &$res, $key, Message $message ) {
69  switch ( $this->messageFormat ) {
70  case 'none':
71  break;
72 
73  case 'wikitext':
74  $res[$key] = $message->setContext( $this->module )->text();
75  break;
76 
77  case 'html':
78  $res[$key] = $message->setContext( $this->module )->parseAsBlock();
79  $res[$key] = Parser::stripOuterParagraph( $res[$key] );
80  break;
81 
82  case 'raw':
83  $res[$key] = [
84  'key' => $message->getKey(),
85  'params' => $message->getParams(),
86  ];
87  break;
88  }
89  }
90 
96  public function securitySensitiveOperation( $operation ) {
97  $status = AuthManager::singleton()->securitySensitiveOperationStatus( $operation );
98  switch ( $status ) {
99  case AuthManager::SEC_OK:
100  return;
101 
102  case AuthManager::SEC_REAUTH:
103  $this->module->dieUsage(
104  'You have not authenticated recently in this session, please reauthenticate.', 'reauthenticate'
105  );
106 
107  case AuthManager::SEC_FAIL:
108  $this->module->dieUsage(
109  'This action is not available as your identify cannot be verified.', 'cannotreauthenticate'
110  );
111 
112  default:
113  throw new UnexpectedValueException( "Unknown status \"$status\"" );
114  }
115  }
116 
123  public static function blacklistAuthenticationRequests( array $reqs, array $blacklist ) {
124  if ( $blacklist ) {
125  $blacklist = array_flip( $blacklist );
126  $reqs = array_filter( $reqs, function ( $req ) use ( $blacklist ) {
127  return !isset( $blacklist[get_class( $req )] );
128  } );
129  }
130  return $reqs;
131  }
132 
138  public function loadAuthenticationRequests( $action ) {
139  $params = $this->module->extractRequestParams();
140 
141  $manager = AuthManager::singleton();
142  $reqs = $manager->getAuthenticationRequests( $action, $this->module->getUser() );
143 
144  // Filter requests, if requested to do so
145  $wantedRequests = null;
146  if ( isset( $params['requests'] ) ) {
147  $wantedRequests = array_flip( $params['requests'] );
148  } elseif ( isset( $params['request'] ) ) {
149  $wantedRequests = [ $params['request'] => true ];
150  }
151  if ( $wantedRequests !== null ) {
152  $reqs = array_filter( $reqs, function ( $req ) use ( $wantedRequests ) {
153  return isset( $wantedRequests[$req->getUniqueId()] );
154  } );
155  }
156 
157  // Collect the fields for all the requests
158  $fields = [];
159  foreach ( $reqs as $req ) {
160  $fields += (array)$req->getFieldInfo();
161  }
162 
163  // Extract the request data for the fields and mark those request
164  // parameters as used
165  $data = array_intersect_key( $this->module->getRequest()->getValues(), $fields );
166  $this->module->getMain()->markParamsUsed( array_keys( $data ) );
167 
168  return AuthenticationRequest::loadRequestsFromSubmission( $reqs, $data );
169  }
170 
177  $params = $this->module->extractRequestParams();
178 
179  $ret = [
180  'status' => $res->status,
181  ];
182 
183  if ( $res->status === AuthenticationResponse::PASS && $res->username !== null ) {
184  $ret['username'] = $res->username;
185  }
186 
187  if ( $res->status === AuthenticationResponse::REDIRECT ) {
188  $ret['redirecttarget'] = $res->redirectTarget;
189  if ( $res->redirectApiData !== null ) {
190  $ret['redirectdata'] = $res->redirectApiData;
191  }
192  }
193 
194  if ( $res->status === AuthenticationResponse::REDIRECT ||
195  $res->status === AuthenticationResponse::UI ||
196  $res->status === AuthenticationResponse::RESTART
197  ) {
198  $ret += $this->formatRequests( $res->neededRequests );
199  }
200 
201  if ( $res->status === AuthenticationResponse::FAIL ||
202  $res->status === AuthenticationResponse::UI ||
203  $res->status === AuthenticationResponse::RESTART
204  ) {
205  $this->formatMessage( $ret, 'message', $res->message );
206  }
207 
208  if ( $res->status === AuthenticationResponse::FAIL ||
209  $res->status === AuthenticationResponse::RESTART
210  ) {
211  $this->module->getRequest()->getSession()->set(
212  'ApiAuthManagerHelper::createRequest',
213  $res->createRequest
214  );
215  $ret['canpreservestate'] = $res->createRequest !== null;
216  } else {
217  $this->module->getRequest()->getSession()->remove( 'ApiAuthManagerHelper::createRequest' );
218  }
219 
220  return $ret;
221  }
222 
227  public function getPreservedRequest() {
228  $ret = $this->module->getRequest()->getSession()->get( 'ApiAuthManagerHelper::createRequest' );
229  return $ret instanceof CreateFromLoginAuthenticationRequest ? $ret : null;
230  }
231 
238  public function formatRequests( array $reqs ) {
239  $params = $this->module->extractRequestParams();
240  $mergeFields = !empty( $params['mergerequestfields'] );
241 
242  $ret = [ 'requests' => [] ];
243  foreach ( $reqs as $req ) {
244  $describe = $req->describeCredentials();
245  $reqInfo = [
246  'id' => $req->getUniqueId(),
247  'metadata' => $req->getMetadata() + [ ApiResult::META_TYPE => 'assoc' ],
248  ];
249  switch ( $req->required ) {
250  case AuthenticationRequest::OPTIONAL:
251  $reqInfo['required'] = 'optional';
252  break;
253  case AuthenticationRequest::REQUIRED:
254  $reqInfo['required'] = 'required';
255  break;
256  case AuthenticationRequest::PRIMARY_REQUIRED:
257  $reqInfo['required'] = 'primary-required';
258  break;
259  }
260  $this->formatMessage( $reqInfo, 'provider', $describe['provider'] );
261  $this->formatMessage( $reqInfo, 'account', $describe['account'] );
262  if ( !$mergeFields ) {
263  $reqInfo['fields'] = $this->formatFields( (array)$req->getFieldInfo() );
264  }
265  $ret['requests'][] = $reqInfo;
266  }
267 
268  if ( $mergeFields ) {
269  $fields = AuthenticationRequest::mergeFieldInfo( $reqs );
270  $ret['fields'] = $this->formatFields( $fields );
271  }
272 
273  return $ret;
274  }
275 
283  private function formatFields( array $fields ) {
284  static $copy = [
285  'type' => true,
286  'value' => true,
287  ];
288 
290  $retFields = [];
291 
292  foreach ( $fields as $name => $field ) {
293  $ret = array_intersect_key( $field, $copy );
294 
295  if ( isset( $field['options'] ) ) {
296  $ret['options'] = array_map( function ( $msg ) use ( $module ) {
297  return $msg->setContext( $module )->plain();
298  }, $field['options'] );
299  ApiResult::setArrayType( $ret['options'], 'assoc' );
300  }
301  $this->formatMessage( $ret, 'label', $field['label'] );
302  $this->formatMessage( $ret, 'help', $field['help'] );
303  $ret['optional'] = !empty( $field['optional'] );
304 
305  $retFields[$name] = $ret;
306  }
307 
308  ApiResult::setArrayType( $retFields, 'assoc' );
309 
310  return $retFields;
311  }
312 
319  public static function getStandardParams( $action, $param /* ... */ ) {
320  $params = [
321  'requests' => [
322  ApiBase::PARAM_TYPE => 'string',
323  ApiBase::PARAM_ISMULTI => true,
324  ApiBase::PARAM_HELP_MSG => [ 'api-help-authmanagerhelper-requests', $action ],
325  ],
326  'request' => [
327  ApiBase::PARAM_TYPE => 'string',
328  ApiBase::PARAM_REQUIRED => true,
329  ApiBase::PARAM_HELP_MSG => [ 'api-help-authmanagerhelper-request', $action ],
330  ],
331  'messageformat' => [
332  ApiBase::PARAM_DFLT => 'wikitext',
333  ApiBase::PARAM_TYPE => [ 'html', 'wikitext', 'raw', 'none' ],
334  ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-messageformat',
335  ],
336  'mergerequestfields' => [
337  ApiBase::PARAM_DFLT => false,
338  ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-mergerequestfields',
339  ],
340  'preservestate' => [
341  ApiBase::PARAM_DFLT => false,
342  ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-preservestate',
343  ],
344  'returnurl' => [
345  ApiBase::PARAM_TYPE => 'string',
346  ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-returnurl',
347  ],
348  'continue' => [
349  ApiBase::PARAM_DFLT => false,
350  ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-continue',
351  ],
352  ];
353 
354  $ret = [];
355  $wantedParams = func_get_args();
356  array_shift( $wantedParams );
357  foreach ( $wantedParams as $name ) {
358  if ( isset( $params[$name] ) ) {
359  $ret[$name] = $params[$name];
360  }
361  }
362  return $ret;
363  }
364 }
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:88
getKey()
Returns the message key.
Definition: Message.php:329
This transfers state between the login and account creation flows.
static getStandardParams($action, $param)
Fetch the standard parameters this helper recognizes.
the array() calling protocol came about after MediaWiki 1.4rc1.
static newForModule(ApiBase $module)
Static version of the constructor, for chaining.
magic word the default is to use $key to get the and $key value or $key value text $key value html to format the value $key
Definition: hooks.txt:2321
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
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 & $ret
Definition: hooks.txt:1798
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:50
const PARAM_REQUIRED
(boolean) Is the parameter required?
Definition: ApiBase.php:112
extractRequestParams($parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:678
const META_TYPE
Key for the 'type' metadata item.
Definition: ApiResult.php:108
This is a value object to hold authentication response data.
formatRequests(array $reqs)
Format an array of AuthenticationRequests for return.
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:1798
getParams()
Returns the message parameters.
Definition: Message.php:340
static stripOuterParagraph($html)
Strip outer.
Definition: Parser.php:6442
ApiBase $module
API module, for context and parameters.
formatMessage(array &$res, $key, Message $message)
Format a message for output.
$res
Definition: database.txt:21
$params
setContext(IContextSource $context)
Set the language and the title from a context object.
Definition: Message.php:678
getPreservedRequest()
Fetch the preserved CreateFromLoginAuthenticationRequest, if any.
__construct(ApiBase $module)
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
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter...
Definition: ApiBase.php:125
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:965
formatFields(array $fields)
Clean up a field array for output.
static blacklistAuthenticationRequests(array $reqs, array $blacklist)
Filter out authentication requests by class name.
securitySensitiveOperation($operation)
Call $manager->securitySensitiveOperationStatus()
formatAuthenticationResponse(AuthenticationResponse $res)
Format an AuthenticationResponse for return.
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:53
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1004
This abstract class implements many basic API functions, and is the base of all API classes...
Definition: ApiBase.php:39
string $messageFormat
Message output format.
static setArrayType(array &$arr, $type, $kvpKeyName=null)
Set the array data type.
Definition: ApiResult.php:730
Helper class for AuthManager-using API modules.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310
loadAuthenticationRequests($action)
Fetch and load the AuthenticationRequests for an action.