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
137 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
138 if ( !$this->mForceDefaultParams
) {
139 return parent
::getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
142 if ( !is_array( $paramSettings ) ) {
143 return $paramSettings;
144 } elseif ( isset( $paramSettings[self
::PARAM_DFLT
] ) ) {
145 return $paramSettings[self
::PARAM_DFLT
];
152 * Set the HTTP status code to be used for the response
156 public function setHttpStatus( $code ) {
157 if ( $this->mDisabled
) {
161 if ( $this->getIsHtml() ) {
162 $this->mHttpStatus
= $code;
164 $this->getMain()->getRequest()->response()->statusHeader( $code );
169 * Initialize the printer function and prepare the output headers.
170 * @param bool $unused Always false since 1.25
172 public function initPrinter( $unused = false ) {
173 if ( $this->mDisabled
) {
177 $mime = $this->getIsWrappedHtml()
178 ?
'text/mediawiki-api-prettyprint-wrapped'
179 : ( $this->getIsHtml() ?
'text/html' : $this->getMimeType() );
181 // Some printers (ex. Feed) do their own header settings,
182 // in which case $mime will be set to null
183 if ( $mime === null ) {
184 return; // skip any initialization
187 $this->getMain()->getRequest()->response()->header( "Content-Type: $mime; charset=utf-8" );
189 // Set X-Frame-Options API results (bug 39180)
190 $apiFrameOptions = $this->getConfig()->get( 'ApiFrameOptions' );
191 if ( $apiFrameOptions ) {
192 $this->getMain()->getRequest()->response()->header( "X-Frame-Options: $apiFrameOptions" );
197 * Finish printing and output buffered data.
199 public function closePrinter() {
200 if ( $this->mDisabled
) {
204 $mime = $this->getMimeType();
205 if ( $this->getIsHtml() && $mime !== null ) {
206 $format = $this->getFormat();
207 $lcformat = strtolower( $format );
208 $result = $this->getBuffer();
210 $context = new DerivativeContext( $this->getMain() );
211 $context->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'apioutput' ) );
212 $context->setTitle( SpecialPage
::getTitleFor( 'ApiHelp' ) );
213 $out = new OutputPage( $context );
214 $context->setOutput( $out );
216 $out->addModuleStyles( 'mediawiki.apipretty' );
217 $out->setPageTitle( $context->msg( 'api-format-title' ) );
219 if ( !$this->getIsWrappedHtml() ) {
220 // When the format without suffix 'fm' is defined, there is a non-html version
221 if ( $this->getMain()->getModuleManager()->isDefined( $lcformat, 'format' ) ) {
222 $msg = $context->msg( 'api-format-prettyprint-header' )->params( $format, $lcformat );
224 $msg = $context->msg( 'api-format-prettyprint-header-only-html' )->params( $format );
227 $header = $msg->parseAsBlock();
229 Html
::rawElement( 'div', [ 'class' => 'api-pretty-header' ],
230 ApiHelp
::fixHelpLinks( $header )
234 if ( $this->mHttpStatus
&& $this->mHttpStatus
!== 200 ) {
236 Html
::rawElement( 'div', [ 'class' => 'api-pretty-header api-pretty-status' ],
238 'api-format-prettyprint-status',
240 HttpStatus
::getMessage( $this->mHttpStatus
)
247 if ( Hooks
::run( 'ApiFormatHighlight', [ $context, $result, $mime, $format ] ) ) {
249 Html
::element( 'pre', [ 'class' => 'api-pretty-content' ], $result )
253 if ( $this->getIsWrappedHtml() ) {
254 // This is a special output mode mainly intended for ApiSandbox use
255 $time = microtime( true ) - $this->getConfig()->get( 'RequestTime' );
256 $json = FormatJson
::encode(
258 'status' => (int)( $this->mHttpStatus ?
: 200 ),
259 'statustext' => HttpStatus
::getMessage( $this->mHttpStatus ?
: 200 ),
260 'html' => $out->getHTML(),
261 'modules' => array_values( array_unique( array_merge(
263 $out->getModuleScripts(),
264 $out->getModuleStyles()
266 'continue' => $this->getResult()->getResultData( 'continue' ),
267 'time' => round( $time * 1000 ),
269 false, FormatJson
::ALL_OK
272 // Bug 66776: wfMangleFlashPolicy() is needed to avoid a nasty bug in
273 // Flash, but what it does isn't friendly for the API, so we need to
275 if ( preg_match( '/\<\s*cross-domain-policy\s*\>/i', $json ) ) {
276 $json = preg_replace(
277 '/\<(\s*cross-domain-policy\s*)\>/i', '\\u003C$1\\u003E', $json
283 // API handles its own clickjacking protection.
284 // Note, that $wgBreakFrames will still override $wgApiFrameOptions for format mode.
285 $out->allowClickjacking();
289 // For non-HTML output, clear all errors that might have been
290 // displayed if display_errors=On
293 echo $this->getBuffer();
298 * Append text to the output buffer.
299 * @param string $text
301 public function printText( $text ) {
302 $this->mBuffer
.= $text;
306 * Get the contents of the buffer.
309 public function getBuffer() {
310 return $this->mBuffer
;
313 public function getAllowedParams() {
315 if ( $this->getIsHtml() ) {
316 $ret['wrappedhtml'] = [
317 ApiBase
::PARAM_DFLT
=> false,
318 ApiBase
::PARAM_HELP_MSG
=> 'apihelp-format-param-wrappedhtml',
325 protected function getExamplesMessages() {
327 'action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName()
328 => [ 'apihelp-format-example-generic', $this->getFormat() ]
332 public function getHelpUrls() {
333 return 'https://www.mediawiki.org/wiki/API:Data_formats';
339 * For really cool vim folding this needs to be at the end:
340 * vim: foldmarker=@{,@} foldmethod=marker