MediaWiki REL1_30
ApiFormatBase.php
Go to the documentation of this file.
1<?php
32abstract class ApiFormatBase extends ApiBase {
34 private $mBuffer, $mDisabled = false;
35 private $mIsWrappedHtml = false;
36 private $mHttpStatus = false;
37 protected $mForceDefaultParams = false;
38
44 public function __construct( ApiMain $main, $format ) {
45 parent::__construct( $main, $format );
46
47 $this->mIsHtml = ( substr( $format, -2, 2 ) === 'fm' ); // ends with 'fm'
48 if ( $this->mIsHtml ) {
49 $this->mFormat = substr( $format, 0, -2 ); // remove ending 'fm'
50 $this->mIsWrappedHtml = $this->getMain()->getCheck( 'wrappedhtml' );
51 } else {
52 $this->mFormat = $format;
53 }
54 $this->mFormat = strtoupper( $this->mFormat );
55 }
56
65 abstract public function getMimeType();
66
75 public function getFilename() {
76 if ( $this->getIsWrappedHtml() ) {
77 return 'api-result-wrapped.json';
78 } elseif ( $this->getIsHtml() ) {
79 return 'api-result.html';
80 } else {
81 $exts = MimeMagic::singleton()->getExtensionsForType( $this->getMimeType() );
82 $ext = $exts ? strtok( $exts, ' ' ) : strtolower( $this->mFormat );
83 return "api-result.$ext";
84 }
85 }
86
91 public function getFormat() {
92 return $this->mFormat;
93 }
94
101 public function getIsHtml() {
102 return $this->mIsHtml;
103 }
104
110 protected function getIsWrappedHtml() {
112 }
113
119 public function disable() {
120 $this->mDisabled = true;
121 }
122
127 public function isDisabled() {
128 return $this->mDisabled;
129 }
130
139 public function canPrintErrors() {
140 return true;
141 }
142
149 public function forceDefaultParams() {
150 $this->mForceDefaultParams = true;
151 }
152
158 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
159 if ( !$this->mForceDefaultParams ) {
160 return parent::getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
161 }
162
163 if ( !is_array( $paramSettings ) ) {
164 return $paramSettings;
165 } elseif ( isset( $paramSettings[self::PARAM_DFLT] ) ) {
166 return $paramSettings[self::PARAM_DFLT];
167 } else {
168 return null;
169 }
170 }
171
177 public function setHttpStatus( $code ) {
178 if ( $this->mDisabled ) {
179 return;
180 }
181
182 if ( $this->getIsHtml() ) {
183 $this->mHttpStatus = $code;
184 } else {
185 $this->getMain()->getRequest()->response()->statusHeader( $code );
186 }
187 }
188
193 public function initPrinter( $unused = false ) {
194 if ( $this->mDisabled ) {
195 return;
196 }
197
198 $mime = $this->getIsWrappedHtml()
199 ? 'text/mediawiki-api-prettyprint-wrapped'
200 : ( $this->getIsHtml() ? 'text/html' : $this->getMimeType() );
201
202 // Some printers (ex. Feed) do their own header settings,
203 // in which case $mime will be set to null
204 if ( $mime === null ) {
205 return; // skip any initialization
206 }
207
208 $this->getMain()->getRequest()->response()->header( "Content-Type: $mime; charset=utf-8" );
209
210 // Set X-Frame-Options API results (T41180)
211 $apiFrameOptions = $this->getConfig()->get( 'ApiFrameOptions' );
212 if ( $apiFrameOptions ) {
213 $this->getMain()->getRequest()->response()->header( "X-Frame-Options: $apiFrameOptions" );
214 }
215
216 // Set a Content-Disposition header so something downloading an API
217 // response uses a halfway-sensible filename (T128209).
218 $filename = $this->getFilename();
219 $this->getMain()->getRequest()->response()->header(
220 "Content-Disposition: inline; filename=\"{$filename}\""
221 );
222 }
223
227 public function closePrinter() {
228 if ( $this->mDisabled ) {
229 return;
230 }
231
232 $mime = $this->getMimeType();
233 if ( $this->getIsHtml() && $mime !== null ) {
234 $format = $this->getFormat();
235 $lcformat = strtolower( $format );
236 $result = $this->getBuffer();
237
238 $context = new DerivativeContext( $this->getMain() );
239 $context->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'apioutput' ) );
240 $context->setTitle( SpecialPage::getTitleFor( 'ApiHelp' ) );
241 $out = new OutputPage( $context );
242 $context->setOutput( $out );
243
244 $out->addModuleStyles( 'mediawiki.apipretty' );
245 $out->setPageTitle( $context->msg( 'api-format-title' ) );
246
247 if ( !$this->getIsWrappedHtml() ) {
248 // When the format without suffix 'fm' is defined, there is a non-html version
249 if ( $this->getMain()->getModuleManager()->isDefined( $lcformat, 'format' ) ) {
250 if ( !$this->getRequest()->wasPosted() ) {
251 $nonHtmlUrl = strtok( $this->getRequest()->getFullRequestURL(), '?' )
252 . '?' . $this->getRequest()->appendQueryValue( 'format', $lcformat );
253 $msg = $context->msg( 'api-format-prettyprint-header-hyperlinked' )
254 ->params( $format, $lcformat, $nonHtmlUrl );
255 } else {
256 $msg = $context->msg( 'api-format-prettyprint-header' )->params( $format, $lcformat );
257 }
258 } else {
259 $msg = $context->msg( 'api-format-prettyprint-header-only-html' )->params( $format );
260 }
261
262 $header = $msg->parseAsBlock();
263 $out->addHTML(
264 Html::rawElement( 'div', [ 'class' => 'api-pretty-header' ],
266 )
267 );
268
269 if ( $this->mHttpStatus && $this->mHttpStatus !== 200 ) {
270 $out->addHTML(
271 Html::rawElement( 'div', [ 'class' => 'api-pretty-header api-pretty-status' ],
272 $this->msg(
273 'api-format-prettyprint-status',
274 $this->mHttpStatus,
275 HttpStatus::getMessage( $this->mHttpStatus )
276 )->parse()
277 )
278 );
279 }
280 }
281
282 if ( Hooks::run( 'ApiFormatHighlight', [ $context, $result, $mime, $format ] ) ) {
283 $out->addHTML(
284 Html::element( 'pre', [ 'class' => 'api-pretty-content' ], $result )
285 );
286 }
287
288 if ( $this->getIsWrappedHtml() ) {
289 // This is a special output mode mainly intended for ApiSandbox use
290 $time = microtime( true ) - $this->getConfig()->get( 'RequestTime' );
291 $json = FormatJson::encode(
292 [
293 'status' => (int)( $this->mHttpStatus ?: 200 ),
294 'statustext' => HttpStatus::getMessage( $this->mHttpStatus ?: 200 ),
295 'html' => $out->getHTML(),
296 'modules' => array_values( array_unique( array_merge(
297 $out->getModules(),
298 $out->getModuleScripts(),
299 $out->getModuleStyles()
300 ) ) ),
301 'continue' => $this->getResult()->getResultData( 'continue' ),
302 'time' => round( $time * 1000 ),
303 ],
304 false, FormatJson::ALL_OK
305 );
306
307 // T68776: wfMangleFlashPolicy() is needed to avoid a nasty bug in
308 // Flash, but what it does isn't friendly for the API, so we need to
309 // work around it.
310 if ( preg_match( '/<\s*cross-domain-policy\s*>/i', $json ) ) {
311 $json = preg_replace(
312 '/<(\s*cross-domain-policy\s*)>/i', '\\u003C$1\\u003E', $json
313 );
314 }
315
316 echo $json;
317 } else {
318 // API handles its own clickjacking protection.
319 // Note, that $wgBreakFrames will still override $wgApiFrameOptions for format mode.
320 $out->allowClickjacking();
321 $out->output();
322 }
323 } else {
324 // For non-HTML output, clear all errors that might have been
325 // displayed if display_errors=On
326 ob_clean();
327
328 echo $this->getBuffer();
329 }
330 }
331
336 public function printText( $text ) {
337 $this->mBuffer .= $text;
338 }
339
344 public function getBuffer() {
345 return $this->mBuffer;
346 }
347
348 public function getAllowedParams() {
349 $ret = [];
350 if ( $this->getIsHtml() ) {
351 $ret['wrappedhtml'] = [
352 ApiBase::PARAM_DFLT => false,
353 ApiBase::PARAM_HELP_MSG => 'apihelp-format-param-wrappedhtml',
354
355 ];
356 }
357 return $ret;
358 }
359
360 protected function getExamplesMessages() {
361 return [
362 'action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName()
363 => [ 'apihelp-format-example-generic', $this->getFormat() ]
364 ];
365 }
366
367 public function getHelpUrls() {
368 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Data_formats';
369 }
370
371}
372
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:41
getModuleManager()
Get the module manager, or null if this module has no sub-modules.
Definition ApiBase.php:295
getMain()
Get the main module.
Definition ApiBase.php:528
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition ApiBase.php:52
getResult()
Get the result object.
Definition ApiBase.php:632
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:128
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:512
This is the abstract base class for API formatters.
getHelpUrls()
Return links to more detailed help pages about the module.
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
__construct(ApiMain $main, $format)
If $format ends with 'fm', pretty-print the output in HTML.
getMimeType()
Overriding class returns the MIME type that should be sent to the client.
getFormat()
Get the internal format name.
getFilename()
Return a filename for this module's output.
printText( $text)
Append text to the output buffer.
initPrinter( $unused=false)
Initialize the printer function and prepare the output headers.
disable()
Disable the formatter.
getBuffer()
Get the contents of the buffer.
getIsWrappedHtml()
Returns true when the special wrapped mode is enabled.
canPrintErrors()
Whether this formatter can handle printing API errors.
getExamplesMessages()
Returns usage examples for this module.
isDisabled()
Whether the printer is disabled.
forceDefaultParams()
Ignore request parameters, force a default.
getIsHtml()
Returns true when the HTML pretty-printer should be used.
getParameterFromSettings( $paramName, $paramSettings, $parseLimit)
Overridden to honor $this->forceDefaultParams(), if applicable @inheritDoc.
setHttpStatus( $code)
Set the HTTP status code to be used for the response.
closePrinter()
Finish printing and output buffered data.
static fixHelpLinks( $html, $helptitle=null, $localModules=[])
Replace Special:ApiHelp links with links to api.php.
Definition ApiHelp.php:174
This is the main API class, used for both external and internal processing.
Definition ApiMain.php:45
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
getRequest()
Get the WebRequest object.
getConfig()
Get the Config object.
IContextSource $context
An IContextSource implementation which will inherit context from another source but allow individual ...
static getMessage( $code)
Get the message associated with an HTTP response status code.
static singleton()
Get an instance of this class.
Definition MimeMagic.php:33
This class should be covered by a general architecture document which does not exist as of January 20...
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition hooks.txt:1778
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition hooks.txt:863
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:1975
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition hooks.txt:862
msg( $key)
This is the method for getting translated interface messages.
if( $ext=='php'|| $ext=='php5') $mime
Definition router.php:59
$header