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, $mUnescapeAmps, $mHelp;
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 * Get the internal format name
71 public function getFormat() {
72 return $this->mFormat
;
76 * Returns true when the HTML pretty-printer should be used.
77 * The default implementation assumes that formats ending with 'fm'
78 * should be formatted in HTML.
81 public function getIsHtml() {
82 return $this->mIsHtml
;
86 * Returns true when the special wrapped mode is enabled.
90 protected function getIsWrappedHtml() {
91 return $this->mIsWrappedHtml
;
95 * Disable the formatter.
97 * This causes calls to initPrinter() and closePrinter() to be ignored.
99 public function disable() {
100 $this->mDisabled
= true;
104 * Whether the printer is disabled
107 public function isDisabled() {
108 return $this->mDisabled
;
112 * Whether this formatter can handle printing API errors.
114 * If this returns false, then on API errors the default printer will be
119 public function canPrintErrors() {
124 * Ignore request parameters, force a default.
126 * Used as a fallback if errors are being thrown.
129 public function forceDefaultParams() {
130 $this->mForceDefaultParams
= true;
134 * Overridden to honor $this->forceDefaultParams(), if applicable
138 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
139 if ( !$this->mForceDefaultParams
) {
140 return parent
::getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
143 if ( !is_array( $paramSettings ) ) {
144 return $paramSettings;
145 } elseif ( isset( $paramSettings[self
::PARAM_DFLT
] ) ) {
146 return $paramSettings[self
::PARAM_DFLT
];
153 * Set the HTTP status code to be used for the response
157 public function setHttpStatus( $code ) {
158 if ( $this->mDisabled
) {
162 if ( $this->getIsHtml() ) {
163 $this->mHttpStatus
= $code;
165 $this->getMain()->getRequest()->response()->statusHeader( $code );
170 * Initialize the printer function and prepare the output headers.
171 * @param bool $unused Always false since 1.25
173 public function initPrinter( $unused = false ) {
174 if ( $this->mDisabled
) {
178 $mime = $this->getIsWrappedHtml()
179 ?
'text/mediawiki-api-prettyprint-wrapped'
180 : ( $this->getIsHtml() ?
'text/html' : $this->getMimeType() );
182 // Some printers (ex. Feed) do their own header settings,
183 // in which case $mime will be set to null
184 if ( $mime === null ) {
185 return; // skip any initialization
188 $this->getMain()->getRequest()->response()->header( "Content-Type: $mime; charset=utf-8" );
190 // Set X-Frame-Options API results (T41180)
191 $apiFrameOptions = $this->getConfig()->get( 'ApiFrameOptions' );
192 if ( $apiFrameOptions ) {
193 $this->getMain()->getRequest()->response()->header( "X-Frame-Options: $apiFrameOptions" );
198 * Finish printing and output buffered data.
200 public function closePrinter() {
201 if ( $this->mDisabled
) {
205 $mime = $this->getMimeType();
206 if ( $this->getIsHtml() && $mime !== null ) {
207 $format = $this->getFormat();
208 $lcformat = strtolower( $format );
209 $result = $this->getBuffer();
211 $context = new DerivativeContext( $this->getMain() );
212 $context->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'apioutput' ) );
213 $context->setTitle( SpecialPage
::getTitleFor( 'ApiHelp' ) );
214 $out = new OutputPage( $context );
215 $context->setOutput( $out );
217 $out->addModuleStyles( 'mediawiki.apipretty' );
218 $out->setPageTitle( $context->msg( 'api-format-title' ) );
220 if ( !$this->getIsWrappedHtml() ) {
221 // When the format without suffix 'fm' is defined, there is a non-html version
222 if ( $this->getMain()->getModuleManager()->isDefined( $lcformat, 'format' ) ) {
223 if ( !$this->getRequest()->wasPosted() ) {
224 $nonHtmlUrl = strtok( $this->getRequest()->getFullRequestURL(), '?' )
225 . '?' . $this->getRequest()->appendQueryValue( 'format', $lcformat );
226 $msg = $context->msg( 'api-format-prettyprint-header-hyperlinked' )
227 ->params( $format, $lcformat, $nonHtmlUrl );
229 $msg = $context->msg( 'api-format-prettyprint-header' )->params( $format, $lcformat );
232 $msg = $context->msg( 'api-format-prettyprint-header-only-html' )->params( $format );
235 $header = $msg->parseAsBlock();
237 Html
::rawElement( 'div', [ 'class' => 'api-pretty-header' ],
238 ApiHelp
::fixHelpLinks( $header )
242 if ( $this->mHttpStatus
&& $this->mHttpStatus
!== 200 ) {
244 Html
::rawElement( 'div', [ 'class' => 'api-pretty-header api-pretty-status' ],
246 'api-format-prettyprint-status',
248 HttpStatus
::getMessage( $this->mHttpStatus
)
255 if ( Hooks
::run( 'ApiFormatHighlight', [ $context, $result, $mime, $format ] ) ) {
257 Html
::element( 'pre', [ 'class' => 'api-pretty-content' ], $result )
261 if ( $this->getIsWrappedHtml() ) {
262 // This is a special output mode mainly intended for ApiSandbox use
263 $time = microtime( true ) - $this->getConfig()->get( 'RequestTime' );
264 $json = FormatJson
::encode(
266 'status' => (int)( $this->mHttpStatus ?
: 200 ),
267 'statustext' => HttpStatus
::getMessage( $this->mHttpStatus ?
: 200 ),
268 'html' => $out->getHTML(),
269 'modules' => array_values( array_unique( array_merge(
271 $out->getModuleScripts(),
272 $out->getModuleStyles()
274 'continue' => $this->getResult()->getResultData( 'continue' ),
275 'time' => round( $time * 1000 ),
277 false, FormatJson
::ALL_OK
280 // T68776: wfMangleFlashPolicy() is needed to avoid a nasty bug in
281 // Flash, but what it does isn't friendly for the API, so we need to
283 if ( preg_match( '/\<\s*cross-domain-policy\s*\>/i', $json ) ) {
284 $json = preg_replace(
285 '/\<(\s*cross-domain-policy\s*)\>/i', '\\u003C$1\\u003E', $json
291 // API handles its own clickjacking protection.
292 // Note, that $wgBreakFrames will still override $wgApiFrameOptions for format mode.
293 $out->allowClickjacking();
297 // For non-HTML output, clear all errors that might have been
298 // displayed if display_errors=On
301 echo $this->getBuffer();
306 * Append text to the output buffer.
307 * @param string $text
309 public function printText( $text ) {
310 $this->mBuffer
.= $text;
314 * Get the contents of the buffer.
317 public function getBuffer() {
318 return $this->mBuffer
;
321 public function getAllowedParams() {
323 if ( $this->getIsHtml() ) {
324 $ret['wrappedhtml'] = [
325 ApiBase
::PARAM_DFLT
=> false,
326 ApiBase
::PARAM_HELP_MSG
=> 'apihelp-format-param-wrappedhtml',
333 protected function getExamplesMessages() {
335 'action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName()
336 => [ 'apihelp-format-example-generic', $this->getFormat() ]
340 public function getHelpUrls() {
341 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Data_formats';
347 * For really cool vim folding this needs to be at the end:
348 * vim: foldmarker=@{,@} foldmethod=marker