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 protected $mForceDefaultParams = false;
39 * If $format ends with 'fm', pretty-print the output in HTML.
40 * @param ApiMain $main
41 * @param string $format Format name
43 public function __construct( ApiMain
$main, $format ) {
44 parent
::__construct( $main, $format );
46 $this->mIsHtml
= ( substr( $format, -2, 2 ) === 'fm' ); // ends with 'fm'
47 if ( $this->mIsHtml
) {
48 $this->mFormat
= substr( $format, 0, -2 ); // remove ending 'fm'
49 $this->mIsWrappedHtml
= $this->getMain()->getCheck( 'wrappedhtml' );
51 $this->mFormat
= $format;
53 $this->mFormat
= strtoupper( $this->mFormat
);
57 * Overriding class returns the MIME type that should be sent to the client.
59 * When getIsHtml() returns true, the return value here is used for syntax
60 * highlighting but the client sees text/html.
64 abstract public function getMimeType();
67 * Get the internal format name
70 public function getFormat() {
71 return $this->mFormat
;
75 * Returns true when the HTML pretty-printer should be used.
76 * The default implementation assumes that formats ending with 'fm'
77 * should be formatted in HTML.
80 public function getIsHtml() {
81 return $this->mIsHtml
;
85 * Returns true when the special wrapped mode is enabled.
89 protected function getIsWrappedHtml() {
90 return $this->mIsWrappedHtml
;
94 * Disable the formatter.
96 * This causes calls to initPrinter() and closePrinter() to be ignored.
98 public function disable() {
99 $this->mDisabled
= true;
103 * Whether the printer is disabled
106 public function isDisabled() {
107 return $this->mDisabled
;
111 * Whether this formatter can handle printing API errors.
113 * If this returns false, then on API errors the default printer will be
118 public function canPrintErrors() {
123 * Ignore request parameters, force a default.
125 * Used as a fallback if errors are being thrown.
128 public function forceDefaultParams() {
129 $this->mForceDefaultParams
= true;
133 * Overridden to honor $this->forceDefaultParams(), if applicable
136 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
137 if ( !$this->mForceDefaultParams
) {
138 return parent
::getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
141 if ( !is_array( $paramSettings ) ) {
142 return $paramSettings;
143 } elseif ( isset( $paramSettings[self
::PARAM_DFLT
] ) ) {
144 return $paramSettings[self
::PARAM_DFLT
];
151 * Initialize the printer function and prepare the output headers.
152 * @param bool $unused Always false since 1.25
154 public function initPrinter( $unused = false ) {
155 if ( $this->mDisabled
) {
159 $mime = $this->getIsWrappedHtml()
160 ?
'text/mediawiki-api-prettyprint-wrapped'
161 : ( $this->getIsHtml() ?
'text/html' : $this->getMimeType() );
163 // Some printers (ex. Feed) do their own header settings,
164 // in which case $mime will be set to null
165 if ( $mime === null ) {
166 return; // skip any initialization
169 $this->getMain()->getRequest()->response()->header( "Content-Type: $mime; charset=utf-8" );
171 // Set X-Frame-Options API results (bug 39180)
172 $apiFrameOptions = $this->getConfig()->get( 'ApiFrameOptions' );
173 if ( $apiFrameOptions ) {
174 $this->getMain()->getRequest()->response()->header( "X-Frame-Options: $apiFrameOptions" );
179 * Finish printing and output buffered data.
181 public function closePrinter() {
182 if ( $this->mDisabled
) {
186 $mime = $this->getMimeType();
187 if ( $this->getIsHtml() && $mime !== null ) {
188 $format = $this->getFormat();
189 $lcformat = strtolower( $format );
190 $result = $this->getBuffer();
192 $context = new DerivativeContext( $this->getMain() );
193 $context->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'apioutput' ) );
194 $context->setTitle( SpecialPage
::getTitleFor( 'ApiHelp' ) );
195 $out = new OutputPage( $context );
196 $context->setOutput( $out );
198 $out->addModuleStyles( 'mediawiki.apipretty' );
199 $out->setPageTitle( $context->msg( 'api-format-title' ) );
201 if ( !$this->getIsWrappedHtml() ) {
202 // When the format without suffix 'fm' is defined, there is a non-html version
203 if ( $this->getMain()->getModuleManager()->isDefined( $lcformat, 'format' ) ) {
204 $msg = $context->msg( 'api-format-prettyprint-header' )->params( $format, $lcformat );
206 $msg = $context->msg( 'api-format-prettyprint-header-only-html' )->params( $format );
209 $header = $msg->parseAsBlock();
211 Html
::rawElement( 'div', [ 'class' => 'api-pretty-header' ],
212 ApiHelp
::fixHelpLinks( $header )
217 if ( Hooks
::run( 'ApiFormatHighlight', [ $context, $result, $mime, $format ] ) ) {
219 Html
::element( 'pre', [ 'class' => 'api-pretty-content' ], $result )
223 if ( $this->getIsWrappedHtml() ) {
224 // This is a special output mode mainly intended for ApiSandbox use
225 $time = microtime( true ) - $this->getConfig()->get( 'RequestTime' );
226 $json = FormatJson
::encode(
228 'html' => $out->getHTML(),
229 'modules' => array_values( array_unique( array_merge(
231 $out->getModuleScripts(),
232 $out->getModuleStyles()
234 'continue' => $this->getResult()->getResultData( 'continue' ),
235 'time' => round( $time * 1000 ),
237 false, FormatJson
::ALL_OK
240 // Bug 66776: wfMangleFlashPolicy() is needed to avoid a nasty bug in
241 // Flash, but what it does isn't friendly for the API, so we need to
243 if ( preg_match( '/\<\s*cross-domain-policy\s*\>/i', $json ) ) {
244 $json = preg_replace(
245 '/\<(\s*cross-domain-policy\s*)\>/i', '\\u003C$1\\u003E', $json
251 // API handles its own clickjacking protection.
252 // Note, that $wgBreakFrames will still override $wgApiFrameOptions for format mode.
253 $out->allowClickjacking();
257 // For non-HTML output, clear all errors that might have been
258 // displayed if display_errors=On
261 echo $this->getBuffer();
266 * Append text to the output buffer.
267 * @param string $text
269 public function printText( $text ) {
270 $this->mBuffer
.= $text;
274 * Get the contents of the buffer.
277 public function getBuffer() {
278 return $this->mBuffer
;
281 public function getAllowedParams() {
283 if ( $this->getIsHtml() ) {
284 $ret['wrappedhtml'] = [
285 ApiBase
::PARAM_DFLT
=> false,
286 ApiBase
::PARAM_HELP_MSG
=> 'apihelp-format-param-wrappedhtml',
293 protected function getExamplesMessages() {
295 'action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName()
296 => [ 'apihelp-format-example-generic', $this->getFormat() ]
300 public function getHelpUrls() {
301 return 'https://www.mediawiki.org/wiki/API:Data_formats';
307 * For really cool vim folding this needs to be at the end:
308 * vim: foldmarker=@{,@} foldmethod=marker