MediaWiki REL1_27
ApiAuthManagerHelper.php
Go to the documentation of this file.
1<?php
28
36
38 private $module;
39
42
46 public function __construct( ApiBase $module ) {
47 $this->module = $module;
48
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 $sensitive = [];
160 foreach ( $reqs as $req ) {
161 $info = (array)$req->getFieldInfo();
162 $fields += $info;
163 $sensitive += array_filter( $info, function ( $opts ) {
164 return !empty( $opts['sensitive'] );
165 } );
166 }
167
168 // Extract the request data for the fields and mark those request
169 // parameters as used
170 $data = array_intersect_key( $this->module->getRequest()->getValues(), $fields );
171 $this->module->getMain()->markParamsUsed( array_keys( $data ) );
172
173 if ( $sensitive ) {
174 $this->module->getMain()->markParamsSensitive( array_keys( $sensitive ) );
175 try {
176 $this->module->requirePostedParameters( array_keys( $sensitive ), 'noprefix' );
177 } catch ( UsageException $ex ) {
178 // Make this a warning for now, upgrade to an error in 1.29.
179 $this->module->setWarning( $ex->getMessage() );
180 $this->module->logFeatureUsage( $this->module->getModuleName() . '-params-in-query-string' );
181 }
182 }
183
184 return AuthenticationRequest::loadRequestsFromSubmission( $reqs, $data );
185 }
186
193 $params = $this->module->extractRequestParams();
194
195 $ret = [
196 'status' => $res->status,
197 ];
198
199 if ( $res->status === AuthenticationResponse::PASS && $res->username !== null ) {
200 $ret['username'] = $res->username;
201 }
202
203 if ( $res->status === AuthenticationResponse::REDIRECT ) {
204 $ret['redirecttarget'] = $res->redirectTarget;
205 if ( $res->redirectApiData !== null ) {
206 $ret['redirectdata'] = $res->redirectApiData;
207 }
208 }
209
210 if ( $res->status === AuthenticationResponse::REDIRECT ||
211 $res->status === AuthenticationResponse::UI ||
212 $res->status === AuthenticationResponse::RESTART
213 ) {
214 $ret += $this->formatRequests( $res->neededRequests );
215 }
216
217 if ( $res->status === AuthenticationResponse::FAIL ||
218 $res->status === AuthenticationResponse::UI ||
219 $res->status === AuthenticationResponse::RESTART
220 ) {
221 $this->formatMessage( $ret, 'message', $res->message );
222 }
223
224 if ( $res->status === AuthenticationResponse::FAIL ||
225 $res->status === AuthenticationResponse::RESTART
226 ) {
227 $this->module->getRequest()->getSession()->set(
228 'ApiAuthManagerHelper::createRequest',
229 $res->createRequest
230 );
231 $ret['canpreservestate'] = $res->createRequest !== null;
232 } else {
233 $this->module->getRequest()->getSession()->remove( 'ApiAuthManagerHelper::createRequest' );
234 }
235
236 return $ret;
237 }
238
243 public function getPreservedRequest() {
244 $ret = $this->module->getRequest()->getSession()->get( 'ApiAuthManagerHelper::createRequest' );
245 return $ret instanceof CreateFromLoginAuthenticationRequest ? $ret : null;
246 }
247
254 public function formatRequests( array $reqs ) {
255 $params = $this->module->extractRequestParams();
256 $mergeFields = !empty( $params['mergerequestfields'] );
257
258 $ret = [ 'requests' => [] ];
259 foreach ( $reqs as $req ) {
260 $describe = $req->describeCredentials();
261 $reqInfo = [
262 'id' => $req->getUniqueId(),
263 'metadata' => $req->getMetadata() + [ ApiResult::META_TYPE => 'assoc' ],
264 ];
265 switch ( $req->required ) {
266 case AuthenticationRequest::OPTIONAL:
267 $reqInfo['required'] = 'optional';
268 break;
269 case AuthenticationRequest::REQUIRED:
270 $reqInfo['required'] = 'required';
271 break;
272 case AuthenticationRequest::PRIMARY_REQUIRED:
273 $reqInfo['required'] = 'primary-required';
274 break;
275 }
276 $this->formatMessage( $reqInfo, 'provider', $describe['provider'] );
277 $this->formatMessage( $reqInfo, 'account', $describe['account'] );
278 if ( !$mergeFields ) {
279 $reqInfo['fields'] = $this->formatFields( (array)$req->getFieldInfo() );
280 }
281 $ret['requests'][] = $reqInfo;
282 }
283
284 if ( $mergeFields ) {
285 $fields = AuthenticationRequest::mergeFieldInfo( $reqs );
286 $ret['fields'] = $this->formatFields( $fields );
287 }
288
289 return $ret;
290 }
291
299 private function formatFields( array $fields ) {
300 static $copy = [
301 'type' => true,
302 'value' => true,
303 ];
304
306 $retFields = [];
307
308 foreach ( $fields as $name => $field ) {
309 $ret = array_intersect_key( $field, $copy );
310
311 if ( isset( $field['options'] ) ) {
312 $ret['options'] = array_map( function ( $msg ) use ( $module ) {
313 return $msg->setContext( $module )->plain();
314 }, $field['options'] );
315 ApiResult::setArrayType( $ret['options'], 'assoc' );
316 }
317 $this->formatMessage( $ret, 'label', $field['label'] );
318 $this->formatMessage( $ret, 'help', $field['help'] );
319 $ret['optional'] = !empty( $field['optional'] );
320
321 $retFields[$name] = $ret;
322 }
323
324 ApiResult::setArrayType( $retFields, 'assoc' );
325
326 return $retFields;
327 }
328
335 public static function getStandardParams( $action, $param /* ... */ ) {
336 $params = [
337 'requests' => [
338 ApiBase::PARAM_TYPE => 'string',
340 ApiBase::PARAM_HELP_MSG => [ 'api-help-authmanagerhelper-requests', $action ],
341 ],
342 'request' => [
343 ApiBase::PARAM_TYPE => 'string',
345 ApiBase::PARAM_HELP_MSG => [ 'api-help-authmanagerhelper-request', $action ],
346 ],
347 'messageformat' => [
348 ApiBase::PARAM_DFLT => 'wikitext',
349 ApiBase::PARAM_TYPE => [ 'html', 'wikitext', 'raw', 'none' ],
350 ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-messageformat',
351 ],
352 'mergerequestfields' => [
353 ApiBase::PARAM_DFLT => false,
354 ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-mergerequestfields',
355 ],
356 'preservestate' => [
357 ApiBase::PARAM_DFLT => false,
358 ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-preservestate',
359 ],
360 'returnurl' => [
361 ApiBase::PARAM_TYPE => 'string',
362 ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-returnurl',
363 ],
364 'continue' => [
365 ApiBase::PARAM_DFLT => false,
366 ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-continue',
367 ],
368 ];
369
370 $ret = [];
371 $wantedParams = func_get_args();
372 array_shift( $wantedParams );
373 foreach ( $wantedParams as $name ) {
374 if ( isset( $params[$name] ) ) {
376 }
377 }
378 return $ret;
379 }
380}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Helper class for AuthManager-using API modules.
getPreservedRequest()
Fetch the preserved CreateFromLoginAuthenticationRequest, if any.
formatAuthenticationResponse(AuthenticationResponse $res)
Format an AuthenticationResponse for return.
static getStandardParams( $action, $param)
Fetch the standard parameters this helper recognizes.
static newForModule(ApiBase $module)
Static version of the constructor, for chaining.
ApiBase $module
API module, for context and parameters.
formatRequests(array $reqs)
Format an array of AuthenticationRequests for return.
formatFields(array $fields)
Clean up a field array for output.
formatMessage(array &$res, $key, Message $message)
Format a message for output.
securitySensitiveOperation( $operation)
Call $manager->securitySensitiveOperationStatus()
static blacklistAuthenticationRequests(array $reqs, array $blacklist)
Filter out authentication requests by class name.
loadAuthenticationRequests( $action)
Fetch and load the AuthenticationRequests for an action.
string $messageFormat
Message output format.
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:39
const PARAM_REQUIRED
(boolean) Is the parameter required?
Definition ApiBase.php:112
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition ApiBase.php:88
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition ApiBase.php:50
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:685
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:125
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition ApiBase.php:53
const META_TYPE
Key for the 'type' metadata item.
static setArrayType(array &$arr, $type, $kvpKeyName=null)
Set the array data type.
This serves as the entry point to the authentication system.
This is a value object for authentication requests.
This is a value object to hold authentication response data.
This transfers state between the login and account creation flows.
The Message class provides methods which fulfil two basic services:
Definition Message.php:159
getParams()
Returns the message parameters.
Definition Message.php:340
getKey()
Returns the message key.
Definition Message.php:329
setContext(IContextSource $context)
Set the language and the title from a context object.
Definition Message.php:678
This exception will be thrown when dieUsage is called to stop module execution.
Definition ApiMain.php:1888
$res
Definition database.txt:21
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
this hook is for auditing only $req
Definition hooks.txt:968
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:1007
the array() calling protocol came about after MediaWiki 1.4rc1.
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:1810
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:1811
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:314
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:37
$params