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, $mCleared;
34 private $mBufferResult = false, $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
);
51 $this->mCleared
= false;
55 * Overriding class returns the MIME type that should be sent to the client.
56 * This method is not called if getIsHtml() returns true.
59 abstract public function getMimeType();
62 * Whether this formatter needs raw data such as _element tags
65 public function getNeedsRawData() {
70 * Get the internal format name
73 public function getFormat() {
74 return $this->mFormat
;
78 * Specify whether or not sequences like &quot; should be unescaped
79 * to " . This should only be set to true for the help message
80 * when rendered in the default (xmlfm) format. This is a temporary
81 * special-case fix that should be removed once the help has been
82 * reworked to use a fully HTML interface.
84 * @deprecated since 1.25
85 * @param bool $b Whether or not ampersands should be escaped.
87 public function setUnescapeAmps( $b ) {
88 wfDeprecated( __METHOD__
, '1.25' );
89 $this->mUnescapeAmps
= $b;
93 * Returns true when the HTML pretty-printer should be used.
94 * The default implementation assumes that formats ending with 'fm'
95 * should be formatted in HTML.
98 public function getIsHtml() {
99 return $this->mIsHtml
;
103 * Whether this formatter can format the help message in a nice way.
104 * By default, this returns the same as getIsHtml().
105 * When action=help is set explicitly, the help will always be shown
106 * @deprecated since 1.25
109 public function getWantsHelp() {
110 wfDeprecated( __METHOD__
, '1.25' );
111 return $this->getIsHtml();
115 * Disable the formatter completely. This causes calls to initPrinter(),
116 * printText() and closePrinter() to be ignored.
118 public function disable() {
119 $this->mDisabled
= true;
122 public function isDisabled() {
123 return $this->mDisabled
;
127 * Whether this formatter can handle printing API errors. If this returns
128 * false, then on API errors the default printer will be instantiated.
132 public function canPrintErrors() {
137 * Initialize the printer function and prepare the output headers, etc.
138 * This method must be the first outputting method during execution.
139 * A human-targeted notice about available formats is printed for the HTML-based output,
140 * except for help screens (caused by either an error in the API parameters,
141 * the calling of action=help, or requesting the root script api.php).
142 * @param bool $unused Always false since 1.25
144 function initPrinter( $unused ) {
145 if ( $this->mDisabled
) {
148 $isHtml = $this->getIsHtml();
149 $mime = $isHtml ?
'text/html' : $this->getMimeType();
150 $script = wfScript( 'api' );
152 // Some printers (ex. Feed) do their own header settings,
153 // in which case $mime will be set to null
154 if ( is_null( $mime ) ) {
155 return; // skip any initialization
158 $this->getMain()->getRequest()->response()->header( "Content-Type: $mime; charset=utf-8" );
160 //Set X-Frame-Options API results (bug 39180)
161 $apiFrameOptions = $this->getConfig()->get( 'ApiFrameOptions' );
162 if ( $apiFrameOptions ) {
163 $this->getMain()->getRequest()->response()->header( "X-Frame-Options: $apiFrameOptions" );
172 if ( $this->mUnescapeAmps
) {
173 ?
> <title
>MediaWiki API
</title
>
176 ?
> <title
>MediaWiki API Result
</title
>
179 // @codingStandardsIgnoreStart Exclude long line from CodeSniffer checks
185 You are looking at the HTML representation of the
<?php
echo $this->mFormat
; ?
> format
.<br
/>
186 HTML is good
for debugging
, but is unsuitable
for application
use.<br
/>
187 Specify the format parameter to change the output format
.<br
/>
188 To see the non HTML representation of the
<?php
echo $this->mFormat
; ?
> format
, set format
=<?php
echo strtolower( $this->mFormat
); ?
>.<br
/>
189 See the
<a href
='https://www.mediawiki.org/wiki/API'>complete documentation
</a
>, or
190 <a href
='<?php echo $script; ?>'>API help
</a
> for more information
.
192 <pre style
='white-space: pre-wrap;'>
194 // @codingStandardsIgnoreEnd
199 * Finish printing. Closes HTML tags.
201 public function closePrinter() {
202 if ( $this->mDisabled
) {
205 if ( $this->getIsHtml() ) {
216 * The main format printing function. Call it to output the result
217 * string to the user. This function will automatically output HTML
218 * when format name ends in 'fm'.
219 * @param string $text
221 public function printText( $text ) {
222 if ( $this->mDisabled
) {
225 if ( $this->mBufferResult
) {
226 $this->mBuffer
= $text;
227 } elseif ( $this->getIsHtml() ) {
228 echo $this->formatHTML( $text );
230 // For non-HTML output, clear all errors that might have been
231 // displayed if display_errors=On
232 // Do this only once, of course
233 if ( !$this->mCleared
) {
235 $this->mCleared
= true;
242 * Get the contents of the buffer.
245 public function getBuffer() {
246 return $this->mBuffer
;
250 * Set the flag to buffer the result instead of printing it.
253 public function setBufferResult( $value ) {
254 $this->mBufferResult
= $value;
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 * @param string $text
273 protected function formatHTML( $text ) {
274 // Escape everything first for full coverage
275 $text = htmlspecialchars( $text );
277 if ( $this->mFormat
=== 'XML' ||
$this->mFormat
=== 'WDDX' ) {
278 // encode all comments or tags as safe blue strings
279 $text = str_replace( '<', '<span style="color:blue;"><', $text );
280 $text = str_replace( '>', '></span>', $text );
283 // identify requests to api.php
284 $text = preg_replace( '#^(\s*)(api\.php\?[^ <\n\t]+)$#m', '\1<a href="\2">\2</a>', $text );
285 if ( $this->mHelp
) {
286 // make lines inside * bold
287 $text = preg_replace( '#^(\s*)(\*[^<>\n]+\*)(\s*)$#m', '$1<b>$2</b>$3', $text );
290 // Armor links (bug 61362)
292 $text = preg_replace_callback( '#<a .*?</a>#', function ( $matches ) use ( &$masked ) {
293 $sha = sha1( $matches[0] );
294 $masked[$sha] = $matches[0];
299 $protos = wfUrlProtocolsWithoutProtRel();
300 // This regex hacks around bug 13218 (" included in the URL)
301 $text = preg_replace(
302 "#(((?i)$protos).*?)(")?([ \\'\"<>\n]|<|>|")#",
303 '<a href="\\1">\\1</a>\\3\\4',
308 $text = preg_replace_callback( '#<([0-9a-f]{40})>#', function ( $matches ) use ( &$masked ) {
310 return isset( $masked[$sha] ) ?
$masked[$sha] : $matches[0];
314 * Temporary fix for bad links in help messages. As a special case,
315 * XML-escaped metachars are de-escaped one level in the help message
316 * for legibility. Should be removed once we have completed a fully-HTML
317 * version of the help message.
319 if ( $this->mUnescapeAmps
) {
320 $text = preg_replace( '/&(amp|quot|lt|gt);/', '&\1;', $text );
326 public function getExamples() {
328 'api.php?action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName()
329 => "Format the query result in the {$this->getModuleName()} format",
333 public function getHelpUrls() {
334 return 'https://www.mediawiki.org/wiki/API:Data_formats';
337 public function getDescription() {
338 return $this->getIsHtml() ?
' (pretty-print in HTML)' : '';
342 * To avoid code duplication with the deprecation of dbg, dump, txt, wddx,
343 * and yaml, this method is added to do the necessary work. It should be
344 * removed when those deprecated formats are removed.
346 protected function markDeprecated() {
347 $fm = $this->getIsHtml() ?
'fm' : '';
348 $name = $this->getModuleName();
349 $this->logFeatureUsage( "format=$name" );
350 $this->setWarning( "format=$name has been deprecated. Please use format=json$fm instead." );