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;
37 * If $format ends with 'fm', pretty-print the output in HTML.
38 * @param ApiMain $main
39 * @param string $format Format name
41 public function __construct( ApiMain
$main, $format ) {
42 parent
::__construct( $main, $format );
44 $this->mIsHtml
= ( substr( $format, -2, 2 ) === 'fm' ); // ends with 'fm'
45 if ( $this->mIsHtml
) {
46 $this->mFormat
= substr( $format, 0, -2 ); // remove ending 'fm'
48 $this->mFormat
= $format;
50 $this->mFormat
= strtoupper( $this->mFormat
);
54 * Overriding class returns the MIME type that should be sent to the client.
56 * When getIsHtml() returns true, the return value here is used for syntax
57 * highlighting but the client sees text/html.
61 abstract public function getMimeType();
64 * Get the internal format name
67 public function getFormat() {
68 return $this->mFormat
;
72 * Returns true when the HTML pretty-printer should be used.
73 * The default implementation assumes that formats ending with 'fm'
74 * should be formatted in HTML.
77 public function getIsHtml() {
78 return $this->mIsHtml
;
82 * Disable the formatter.
84 * This causes calls to initPrinter() and closePrinter() to be ignored.
86 public function disable() {
87 $this->mDisabled
= true;
91 * Whether the printer is disabled
94 public function isDisabled() {
95 return $this->mDisabled
;
99 * Whether this formatter can handle printing API errors.
101 * If this returns false, then on API errors the default printer will be
106 public function canPrintErrors() {
111 * Initialize the printer function and prepare the output headers.
112 * @param bool $unused Always false since 1.25
114 function initPrinter( $unused = false ) {
115 if ( $this->mDisabled
) {
119 $mime = $this->getIsHtml() ?
'text/html' : $this->getMimeType();
121 // Some printers (ex. Feed) do their own header settings,
122 // in which case $mime will be set to null
123 if ( $mime === null ) {
124 return; // skip any initialization
127 $this->getMain()->getRequest()->response()->header( "Content-Type: $mime; charset=utf-8" );
129 //Set X-Frame-Options API results (bug 39180)
130 $apiFrameOptions = $this->getConfig()->get( 'ApiFrameOptions' );
131 if ( $apiFrameOptions ) {
132 $this->getMain()->getRequest()->response()->header( "X-Frame-Options: $apiFrameOptions" );
137 * Finish printing and output buffered data.
139 public function closePrinter() {
140 if ( $this->mDisabled
) {
144 $mime = $this->getMimeType();
145 if ( $this->getIsHtml() && $mime !== null ) {
146 $format = $this->getFormat();
147 $result = $this->getBuffer();
149 $context = new DerivativeContext( $this->getMain() );
150 $context->setSkin( SkinFactory
::getDefaultInstance()->makeSkin( 'apioutput' ) );
151 $context->setTitle( SpecialPage
::getTitleFor( 'ApiHelp' ) );
152 $out = new OutputPage( $context );
153 $context->setOutput( $out );
155 $out->addModules( 'mediawiki.apipretty' );
156 $out->setPageTitle( $context->msg( 'api-format-title' ) );
158 $header = $context->msg( 'api-format-prettyprint-header' )
159 ->params( $format, strtolower( $format ) )
162 Html
::rawElement( 'div', array( 'class' => 'api-pretty-header' ),
163 ApiHelp
::fixHelpLinks( $header )
167 if ( Hooks
::run( 'ApiFormatHighlight', array( $context, $result, $mime, $format ) ) ) {
169 Html
::element( 'pre', array( 'class' => 'api-pretty-content' ), $result )
173 // API handles its own clickjacking protection.
174 // Note, that $wgBreakFrames will still override $wgApiFrameOptions for format mode.
175 $out->allowClickJacking();
178 // For non-HTML output, clear all errors that might have been
179 // displayed if display_errors=On
182 echo $this->getBuffer();
187 * Append text to the output buffer.
188 * @param string $text
190 public function printText( $text ) {
191 $this->mBuffer
.= $text;
195 * Get the contents of the buffer.
198 public function getBuffer() {
199 return $this->mBuffer
;
202 protected function getExamplesMessages() {
204 'action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName()
205 => array( 'apihelp-format-example-generic', $this->getFormat() )
209 public function getHelpUrls() {
210 return 'https://www.mediawiki.org/wiki/API:Data_formats';
214 * To avoid code duplication with the deprecation of dbg, dump, txt, wddx,
215 * and yaml, this method is added to do the necessary work. It should be
216 * removed when those deprecated formats are removed.
218 protected function markDeprecated() {
219 $fm = $this->getIsHtml() ?
'fm' : '';
220 $name = $this->getModuleName();
221 $this->logFeatureUsage( "format=$name" );
222 $this->setWarning( "format=$name has been deprecated. Please use format=json$fm instead." );
225 /************************************************************************//**
231 * Specify whether or not sequences like &quot; should be unescaped
232 * to " . This should only be set to true for the help message
233 * when rendered in the default (xmlfm) format. This is a temporary
234 * special-case fix that should be removed once the help has been
235 * reworked to use a fully HTML interface.
237 * @deprecated since 1.25
238 * @param bool $b Whether or not ampersands should be escaped.
240 public function setUnescapeAmps( $b ) {
241 wfDeprecated( __METHOD__
, '1.25' );
242 $this->mUnescapeAmps
= $b;
246 * Whether this formatter can format the help message in a nice way.
247 * By default, this returns the same as getIsHtml().
248 * When action=help is set explicitly, the help will always be shown
249 * @deprecated since 1.25
252 public function getWantsHelp() {
253 wfDeprecated( __METHOD__
, '1.25' );
254 return $this->getIsHtml();
258 * Sets whether the pretty-printer should format *bold*
259 * @deprecated since 1.25
262 public function setHelp( $help = true ) {
263 wfDeprecated( __METHOD__
, '1.25' );
264 $this->mHelp
= $help;
268 * Pretty-print various elements in HTML format, such as xml tags and
269 * URLs. This method also escapes characters like <
270 * @deprecated since 1.25
271 * @param string $text
274 protected function formatHTML( $text ) {
275 wfDeprecated( __METHOD__
, '1.25' );
277 // Escape everything first for full coverage
278 $text = htmlspecialchars( $text );
280 if ( $this->mFormat
=== 'XML' ||
$this->mFormat
=== 'WDDX' ) {
281 // encode all comments or tags as safe blue strings
282 $text = str_replace( '<', '<span style="color:blue;"><', $text );
283 $text = str_replace( '>', '></span>', $text );
286 // identify requests to api.php
287 $text = preg_replace( '#^(\s*)(api\.php\?[^ <\n\t]+)$#m', '\1<a href="\2">\2</a>', $text );
288 if ( $this->mHelp
) {
289 // make lines inside * bold
290 $text = preg_replace( '#^(\s*)(\*[^<>\n]+\*)(\s*)$#m', '$1<b>$2</b>$3', $text );
293 // Armor links (bug 61362)
295 $text = preg_replace_callback( '#<a .*?</a>#', function ( $matches ) use ( &$masked ) {
296 $sha = sha1( $matches[0] );
297 $masked[$sha] = $matches[0];
302 $protos = wfUrlProtocolsWithoutProtRel();
303 // This regex hacks around bug 13218 (" included in the URL)
304 $text = preg_replace(
305 "#(((?i)$protos).*?)(")?([ \\'\"<>\n]|<|>|")#",
306 '<a href="\\1">\\1</a>\\3\\4',
311 $text = preg_replace_callback( '#<([0-9a-f]{40})>#', function ( $matches ) use ( &$masked ) {
313 return isset( $masked[$sha] ) ?
$masked[$sha] : $matches[0];
317 * Temporary fix for bad links in help messages. As a special case,
318 * XML-escaped metachars are de-escaped one level in the help message
319 * for legibility. Should be removed once we have completed a fully-HTML
320 * version of the help message.
322 if ( $this->mUnescapeAmps
) {
323 $text = preg_replace( '/&(amp|quot|lt|gt);/', '&\1;', $text );
330 * @see ApiBase::getDescription
331 * @deprecated since 1.25
333 public function getDescription() {
334 return $this->getIsHtml() ?
' (pretty-print in HTML)' : '';
338 * Set the flag to buffer the result instead of printing it.
339 * @deprecated since 1.25, output is always buffered
342 public function setBufferResult( $value ) {
346 * Formerly indicated whether the formatter needed metadata from ApiResult.
348 * ApiResult previously (indirectly) used this to decide whether to add
349 * metadata or to ignore calls to metadata-setting methods, which
350 * unfortunately made several methods that should have been static have to
351 * be dynamic instead. Now ApiResult always stores metadata and formatters
352 * are required to ignore it or filter it out.
354 * @deprecated since 1.25
357 public function getNeedsRawData() {
365 * For really cool vim folding this needs to be at the end:
366 * vim: foldmarker=@{,@} foldmethod=marker