3 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 namespace MediaWiki\Api
;
26 use MediaWiki\Context\DerivativeContext
;
27 use MediaWiki\Html\Html
;
28 use MediaWiki\Json\FormatJson
;
29 use MediaWiki\MainConfigNames
;
30 use MediaWiki\MediaWikiServices
;
31 use MediaWiki\Output\OutputPage
;
32 use MediaWiki\SpecialPage\SpecialPage
;
33 use Wikimedia\ParamValidator\ParamValidator
;
36 * This is the abstract base class for API formatters.
40 abstract class ApiFormatBase
extends ApiBase
{
41 private bool $mIsHtml;
42 private string $mFormat;
43 private string $mBuffer = '';
44 private bool $mDisabled = false;
46 private $mIsWrappedHtml = false;
48 private $mHttpStatus = false;
50 protected $mForceDefaultParams = false;
53 * If $format ends with 'fm', pretty-print the output in HTML.
55 * @param ApiMain $main
56 * @param string $format Format name
58 public function __construct( ApiMain
$main, string $format ) {
59 parent
::__construct( $main, $format );
61 $this->mIsHtml
= str_ends_with( $format, 'fm' );
62 if ( $this->mIsHtml
) {
63 $this->mFormat
= substr( $format, 0, -2 ); // remove ending 'fm'
64 $this->mIsWrappedHtml
= $this->getMain()->getCheck( 'wrappedhtml' );
66 $this->mFormat
= $format;
68 $this->mFormat
= strtoupper( $this->mFormat
);
72 * Overriding class returns the MIME type that should be sent to the client.
74 * When getIsHtml() returns true, the return value here is used for syntax
75 * highlighting, but the client sees text/html.
79 abstract public function getMimeType();
82 * Return a filename for this module's output.
84 * @note If $this->getIsWrappedHtml() || $this->getIsHtml(), you'll very
85 * likely want to fall back to this class's version.
87 * @return string Generally, this should be "api-result.$ext"
89 public function getFilename() {
90 if ( $this->getIsWrappedHtml() ) {
91 return 'api-result-wrapped.json';
94 if ( $this->getIsHtml() ) {
95 return 'api-result.html';
98 $mimeAnalyzer = MediaWikiServices
::getInstance()->getMimeAnalyzer();
99 $ext = $mimeAnalyzer->getExtensionFromMimeTypeOrNull( $this->getMimeType() )
100 ??
strtolower( $this->mFormat
);
101 return "api-result.$ext";
105 * Get the internal format name
109 public function getFormat() {
110 return $this->mFormat
;
114 * Returns true when the HTML pretty-printer should be used.
115 * The default implementation assumes that formats ending with 'fm' should be formatted in HTML.
119 public function getIsHtml() {
120 return $this->mIsHtml
;
124 * Returns true when the special-wrapped mode is enabled.
129 protected function getIsWrappedHtml() {
130 return $this->mIsWrappedHtml
;
134 * Disable the formatter.
136 * This causes calls to initPrinter() and closePrinter() to be ignored.
138 public function disable() {
139 $this->mDisabled
= true;
143 * Whether the printer is disabled.
147 public function isDisabled() {
148 return $this->mDisabled
;
152 * Whether this formatter can handle printing API errors.
154 * If this returns false, then when API errors occur, the default printer will be instantiated.
158 public function canPrintErrors() {
163 * Ignore request parameters, force a default.
165 * Used as a fallback if errors are being thrown.
169 public function forceDefaultParams() {
170 $this->mForceDefaultParams
= true;
174 * Overridden to honor $this->forceDefaultParams(), if applicable
178 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
179 if ( !$this->mForceDefaultParams
) {
180 return parent
::getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
183 if ( !is_array( $paramSettings ) ) {
184 return $paramSettings;
187 return $paramSettings[ParamValidator
::PARAM_DEFAULT
] ??
null;
191 * Set the HTTP status code to be used for the response
195 public function setHttpStatus( $code ) {
196 if ( $this->mDisabled
) {
200 if ( $this->getIsHtml() ) {
201 $this->mHttpStatus
= $code;
203 $this->getMain()->getRequest()->response()->statusHeader( $code );
208 * Initialize the printer function and prepare the output headers.
209 * @param bool $unused Always false since 1.25
211 public function initPrinter( $unused = false ) {
212 if ( $this->mDisabled
) {
216 if ( $this->getIsHtml() && $this->getMain()->getCacheMode() === 'public' ) {
217 // The HTML may contain user secrets! T354045
218 $this->getMain()->setCacheMode( 'anon-public-user-private' );
221 $mime = $this->getIsWrappedHtml()
222 ?
'text/mediawiki-api-prettyprint-wrapped'
223 : ( $this->getIsHtml() ?
'text/html' : $this->getMimeType() );
225 // Some printers (ex. Feed) do their own header settings,
226 // in which case $mime will be set to null
227 if ( $mime === null ) {
228 return; // skip any initialization
231 $this->getMain()->getRequest()->response()->header( "Content-Type: $mime; charset=utf-8" );
233 // Set X-Frame-Options API results (T41180)
234 $apiFrameOptions = $this->getConfig()->get( MainConfigNames
::ApiFrameOptions
);
235 if ( $apiFrameOptions ) {
236 $this->getMain()->getRequest()->response()->header( "X-Frame-Options: $apiFrameOptions" );
239 // Set a Content-Disposition header so something downloading an API
240 // response uses a halfway-sensible filename (T128209).
241 $header = 'Content-Disposition: inline';
242 $filename = $this->getFilename();
243 $compatFilename = mb_convert_encoding( $filename, 'ISO-8859-1' );
244 if ( preg_match( '/^[0-9a-zA-Z!#$%&\'*+\-.^_`|~]+$/', $compatFilename ) ) {
245 $header .= '; filename=' . $compatFilename;
247 $header .= '; filename="'
248 . preg_replace( '/([\0-\x1f"\x5c\x7f])/', '\\\\$1', $compatFilename ) . '"';
250 if ( $compatFilename !== $filename ) {
251 $value = "UTF-8''" . rawurlencode( $filename );
252 // rawurlencode() encodes more characters than RFC 5987 specifies. Unescape the ones it allows.
253 $value = strtr( $value, [
254 '%21' => '!', '%23' => '#', '%24' => '$', '%26' => '&', '%2B' => '+', '%5E' => '^',
255 '%60' => '`', '%7C' => '|',
257 $header .= '; filename*=' . $value;
259 $this->getMain()->getRequest()->response()->header( $header );
263 * Finish printing and output buffered data.
265 public function closePrinter() {
266 if ( $this->mDisabled
) {
270 $mime = $this->getMimeType();
271 if ( $this->getIsHtml() && $mime !== null ) {
272 $format = $this->getFormat();
273 $lcformat = strtolower( $format );
274 $result = $this->getBuffer();
276 $context = new DerivativeContext( $this->getMain() );
277 $skinFactory = MediaWikiServices
::getInstance()->getSkinFactory();
278 $context->setSkin( $skinFactory->makeSkin( 'apioutput' ) );
279 $context->setTitle( SpecialPage
::getTitleFor( 'ApiHelp' ) );
280 $out = new OutputPage( $context );
281 $context->setOutput( $out );
283 $out->setRobotPolicy( 'noindex,nofollow' );
284 $out->addModuleStyles( 'mediawiki.apipretty' );
285 $out->setPageTitleMsg( $context->msg( 'api-format-title' ) );
287 if ( !$this->getIsWrappedHtml() ) {
288 // When the format without suffix 'fm' is defined, there is a non-html version
289 if ( $this->getMain()->getModuleManager()->isDefined( $lcformat, 'format' ) ) {
290 if ( !$this->getRequest()->wasPosted() ) {
291 $nonHtmlUrl = strtok( $this->getRequest()->getFullRequestURL(), '?' )
292 . '?' . $this->getRequest()->appendQueryValue( 'format', $lcformat );
293 $msg = $context->msg( 'api-format-prettyprint-header-hyperlinked' )
294 ->params( $format, $lcformat, $nonHtmlUrl );
296 $msg = $context->msg( 'api-format-prettyprint-header' )->params( $format, $lcformat );
299 $msg = $context->msg( 'api-format-prettyprint-header-only-html' )->params( $format );
302 $header = $msg->parseAsBlock();
304 Html
::rawElement( 'div', [ 'class' => 'api-pretty-header' ],
305 ApiHelp
::fixHelpLinks( $header )
309 if ( $this->mHttpStatus
&& $this->mHttpStatus
!== 200 ) {
311 Html
::rawElement( 'div', [ 'class' => [ 'api-pretty-header', 'api-pretty-status' ] ],
313 'api-format-prettyprint-status',
315 HttpStatus
::getMessage( $this->mHttpStatus
)
322 if ( $this->getHookRunner()->onApiFormatHighlight( $context, $result, $mime, $format ) ) {
324 Html
::element( 'pre', [ 'class' => 'api-pretty-content' ], $result )
328 if ( $this->getIsWrappedHtml() ) {
329 // This is a special output mode mainly intended for ApiSandbox use
330 $time = $this->getMain()->getRequest()->getElapsedTime();
331 echo FormatJson
::encode(
333 'status' => (int)( $this->mHttpStatus ?
: 200 ),
334 'statustext' => HttpStatus
::getMessage( $this->mHttpStatus ?
: 200 ),
335 'html' => $out->getHTML(),
336 'modules' => array_values( array_unique( array_merge(
338 $out->getModuleStyles()
340 'continue' => $this->getResult()->getResultData( 'continue' ),
341 'time' => round( $time * 1000 ),
343 false, FormatJson
::ALL_OK
346 // API handles its own clickjacking protection.
347 // Note: $wgBreakFrames will still override $wgApiFrameOptions for format mode.
348 $out->getMetadata()->setPreventClickjacking( false );
352 // For non-HTML output, clear all errors that might have been
353 // displayed if display_errors=On
356 echo $this->getBuffer();
361 * Append text to the output buffer.
363 * @param string $text
365 public function printText( $text ) {
366 $this->mBuffer
.= $text;
370 * Get the contents of the buffer.
374 public function getBuffer() {
375 return $this->mBuffer
;
378 public function getAllowedParams() {
380 if ( $this->getIsHtml() ) {
381 $ret['wrappedhtml'] = [
382 ParamValidator
::PARAM_DEFAULT
=> false,
383 ApiBase
::PARAM_HELP_MSG
=> 'apihelp-format-param-wrappedhtml',
389 protected function getExamplesMessages() {
391 'action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName()
392 => [ 'apihelp-format-example-generic', $this->getFormat() ]
396 public function getHelpUrls() {
397 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Data_formats';
403 * For really cool vim folding this needs to be at the end:
404 * vim: foldmarker=@{,@} foldmethod=marker
407 /** @deprecated class alias since 1.43 */
408 class_alias( ApiFormatBase
::class, 'ApiFormatBase' );