5 * Created on Sep 19, 2006
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
28 * This is the abstract base class for API formatters.
32 abstract class ApiFormatBase
extends ApiBase
{
33 private $mIsHtml, $mFormat;
34 private $mBuffer, $mDisabled = false;
35 private $mIsWrappedHtml = false;
36 private $mHttpStatus = false;
37 protected $mForceDefaultParams = false;
40 * If $format ends with 'fm', pretty-print the output in HTML.
41 * @param ApiMain $main
42 * @param string $format Format name
44 public function __construct( ApiMain
$main, $format ) {
45 parent
::__construct( $main, $format );
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' );
52 $this->mFormat
= $format;
54 $this->mFormat
= strtoupper( $this->mFormat
);
58 * Overriding class returns the MIME type that should be sent to the client.
60 * When getIsHtml() returns true, the return value here is used for syntax
61 * highlighting but the client sees text/html.
65 abstract public function getMimeType();
68 * Return a filename for this module's output.
69 * @note If $this->getIsWrappedHtml() || $this->getIsHtml(), you'll very
70 * likely want to fall back to this class's version.
72 * @return string Generally this should be "api-result.$ext", and must be
73 * encoded for inclusion in a Content-Disposition header's filename parameter.
75 public function getFilename() {
76 if ( $this->getIsWrappedHtml() ) {
77 return 'api-result-wrapped.json';
78 } elseif ( $this->getIsHtml() ) {
79 return 'api-result.html';
81 $exts = MediaWiki\MediaWikiServices
::getInstance()->getMimeAnalyzer()
82 ->getExtensionsForType( $this->getMimeType() );
83 $ext = $exts ?
strtok( $exts, ' ' ) : strtolower( $this->mFormat
);
84 return "api-result.$ext";
89 * Get the internal format name
92 public function getFormat() {
93 return $this->mFormat
;
97 * Returns true when the HTML pretty-printer should be used.
98 * The default implementation assumes that formats ending with 'fm'
99 * should be formatted in HTML.
102 public function getIsHtml() {
103 return $this->mIsHtml
;
107 * Returns true when the special wrapped mode is enabled.
111 protected function getIsWrappedHtml() {
112 return $this->mIsWrappedHtml
;
116 * Disable the formatter.
118 * This causes calls to initPrinter() and closePrinter() to be ignored.
120 public function disable() {
121 $this->mDisabled
= true;
125 * Whether the printer is disabled
128 public function isDisabled() {
129 return $this->mDisabled
;
133 * Whether this formatter can handle printing API errors.
135 * If this returns false, then on API errors the default printer will be
140 public function canPrintErrors() {
145 * Ignore request parameters, force a default.
147 * Used as a fallback if errors are being thrown.
150 public function forceDefaultParams() {
151 $this->mForceDefaultParams
= true;
155 * Overridden to honor $this->forceDefaultParams(), if applicable
159 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
160 if ( !$this->mForceDefaultParams
) {
161 return parent
::getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
164 if ( !is_array( $paramSettings ) ) {
165 return $paramSettings;
166 } elseif ( isset( $paramSettings[self
::PARAM_DFLT
] ) ) {
167 return $paramSettings[self
::PARAM_DFLT
];
174 * Set the HTTP status code to be used for the response
178 public function setHttpStatus( $code ) {
179 if ( $this->mDisabled
) {
183 if ( $this->getIsHtml() ) {
184 $this->mHttpStatus
= $code;
186 $this->getMain()->getRequest()->response()->statusHeader( $code );
191 * Initialize the printer function and prepare the output headers.
192 * @param bool $unused Always false since 1.25
194 public function initPrinter( $unused = false ) {
195 if ( $this->mDisabled
) {
199 $mime = $this->getIsWrappedHtml()
200 ?
'text/mediawiki-api-prettyprint-wrapped'
201 : ( $this->getIsHtml() ?
'text/html' : $this->getMimeType() );
203 // Some printers (ex. Feed) do their own header settings,
204 // in which case $mime will be set to null
205 if ( $mime === null ) {
206 return; // skip any initialization
209 $this->getMain()->getRequest()->response()->header( "Content-Type: $mime; charset=utf-8" );
211 // Set X-Frame-Options API results (T41180)
212 $apiFrameOptions = $this->getConfig()->get( 'ApiFrameOptions' );
213 if ( $apiFrameOptions ) {
214 $this->getMain()->getRequest()->response()->header( "X-Frame-Options: $apiFrameOptions" );
217 // Set a Content-Disposition header so something downloading an API
218 // response uses a halfway-sensible filename (T128209).
219 $filename = $this->getFilename();
220 $this->getMain()->getRequest()->response()->header(
221 "Content-Disposition: inline; filename=\"{$filename}\""
226 * Finish printing and output buffered data.
228 public function closePrinter() {
229 if ( $this->mDisabled
) {
233 $mime = $this->getMimeType();
234 if ( $this->getIsHtml() && $mime !== null ) {
235 $format = $this->getFormat();
236 $lcformat = strtolower( $format );
237 $result = $this->getBuffer();
239 $context = new DerivativeContext( $this->getMain() );
240 $context->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'apioutput' ) );
241 $context->setTitle( SpecialPage
::getTitleFor( 'ApiHelp' ) );
242 $out = new OutputPage( $context );
243 $context->setOutput( $out );
245 $out->addModuleStyles( 'mediawiki.apipretty' );
246 $out->setPageTitle( $context->msg( 'api-format-title' ) );
248 if ( !$this->getIsWrappedHtml() ) {
249 // When the format without suffix 'fm' is defined, there is a non-html version
250 if ( $this->getMain()->getModuleManager()->isDefined( $lcformat, 'format' ) ) {
251 if ( !$this->getRequest()->wasPosted() ) {
252 $nonHtmlUrl = strtok( $this->getRequest()->getFullRequestURL(), '?' )
253 . '?' . $this->getRequest()->appendQueryValue( 'format', $lcformat );
254 $msg = $context->msg( 'api-format-prettyprint-header-hyperlinked' )
255 ->params( $format, $lcformat, $nonHtmlUrl );
257 $msg = $context->msg( 'api-format-prettyprint-header' )->params( $format, $lcformat );
260 $msg = $context->msg( 'api-format-prettyprint-header-only-html' )->params( $format );
263 $header = $msg->parseAsBlock();
265 Html
::rawElement( 'div', [ 'class' => 'api-pretty-header' ],
266 ApiHelp
::fixHelpLinks( $header )
270 if ( $this->mHttpStatus
&& $this->mHttpStatus
!== 200 ) {
272 Html
::rawElement( 'div', [ 'class' => 'api-pretty-header api-pretty-status' ],
274 'api-format-prettyprint-status',
276 HttpStatus
::getMessage( $this->mHttpStatus
)
283 if ( Hooks
::run( 'ApiFormatHighlight', [ $context, $result, $mime, $format ] ) ) {
285 Html
::element( 'pre', [ 'class' => 'api-pretty-content' ], $result )
289 if ( $this->getIsWrappedHtml() ) {
290 // This is a special output mode mainly intended for ApiSandbox use
291 $time = microtime( true ) - $this->getConfig()->get( 'RequestTime' );
292 $json = FormatJson
::encode(
294 'status' => (int)( $this->mHttpStatus ?
: 200 ),
295 'statustext' => HttpStatus
::getMessage( $this->mHttpStatus ?
: 200 ),
296 'html' => $out->getHTML(),
297 'modules' => array_values( array_unique( array_merge(
299 $out->getModuleScripts(),
300 $out->getModuleStyles()
302 'continue' => $this->getResult()->getResultData( 'continue' ),
303 'time' => round( $time * 1000 ),
305 false, FormatJson
::ALL_OK
308 // T68776: wfMangleFlashPolicy() is needed to avoid a nasty bug in
309 // Flash, but what it does isn't friendly for the API, so we need to
311 if ( preg_match( '/\<\s*cross-domain-policy\s*\>/i', $json ) ) {
312 $json = preg_replace(
313 '/\<(\s*cross-domain-policy\s*)\>/i', '\\u003C$1\\u003E', $json
319 // API handles its own clickjacking protection.
320 // Note, that $wgBreakFrames will still override $wgApiFrameOptions for format mode.
321 $out->allowClickjacking();
325 // For non-HTML output, clear all errors that might have been
326 // displayed if display_errors=On
329 echo $this->getBuffer();
334 * Append text to the output buffer.
335 * @param string $text
337 public function printText( $text ) {
338 $this->mBuffer
.= $text;
342 * Get the contents of the buffer.
345 public function getBuffer() {
346 return $this->mBuffer
;
349 public function getAllowedParams() {
351 if ( $this->getIsHtml() ) {
352 $ret['wrappedhtml'] = [
353 ApiBase
::PARAM_DFLT
=> false,
354 ApiBase
::PARAM_HELP_MSG
=> 'apihelp-format-param-wrappedhtml',
361 protected function getExamplesMessages() {
363 'action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName()
364 => [ 'apihelp-format-example-generic', $this->getFormat() ]
368 public function getHelpUrls() {
369 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Data_formats';
375 * For really cool vim folding this needs to be at the end:
376 * vim: foldmarker=@{,@} foldmethod=marker