Expose $wgMaxArticleSize in siteinfo query api
[mediawiki.git] / includes / api / ApiFormatBase.php
blobc826bbad9569cd8a924b2c95f81e0a94ae581611
1 <?php
2 /**
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
24 * @file
27 /**
28 * This is the abstract base class for API formatters.
30 * @ingroup API
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;
38 /**
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' );
50 } else {
51 $this->mFormat = $format;
53 $this->mFormat = strtoupper( $this->mFormat );
56 /**
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.
62 * @return string
64 abstract public function getMimeType();
66 /**
67 * Get the internal format name
68 * @return string
70 public function getFormat() {
71 return $this->mFormat;
74 /**
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.
78 * @return bool
80 public function getIsHtml() {
81 return $this->mIsHtml;
84 /**
85 * Returns true when the special wrapped mode is enabled.
86 * @since 1.27
87 * @return bool
89 protected function getIsWrappedHtml() {
90 return $this->mIsWrappedHtml;
93 /**
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
104 * @return bool
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
114 * instantiated.
115 * @since 1.23
116 * @return bool
118 public function canPrintErrors() {
119 return true;
123 * Ignore request parameters, force a default.
125 * Used as a fallback if errors are being thrown.
126 * @since 1.26
128 public function forceDefaultParams() {
129 $this->mForceDefaultParams = true;
133 * Overridden to honor $this->forceDefaultParams(), if applicable
134 * @since 1.26
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];
145 } else {
146 return null;
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 ) {
156 return;
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 ) {
183 return;
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 );
205 } else {
206 $msg = $context->msg( 'api-format-prettyprint-header-only-html' )->params( $format );
209 $header = $msg->parseAsBlock();
210 $out->addHTML(
211 Html::rawElement( 'div', [ 'class' => 'api-pretty-header' ],
212 ApiHelp::fixHelpLinks( $header )
217 if ( Hooks::run( 'ApiFormatHighlight', [ $context, $result, $mime, $format ] ) ) {
218 $out->addHTML(
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(
230 $out->getModules(),
231 $out->getModuleScripts(),
232 $out->getModuleStyles()
233 ) ) ),
234 'time' => round( $time * 1000 ),
236 false, FormatJson::ALL_OK
239 // Bug 66776: wfMangleFlashPolicy() is needed to avoid a nasty bug in
240 // Flash, but what it does isn't friendly for the API, so we need to
241 // work around it.
242 if ( preg_match( '/\<\s*cross-domain-policy\s*\>/i', $json ) ) {
243 $json = preg_replace(
244 '/\<(\s*cross-domain-policy\s*)\>/i', '\\u003C$1\\u003E', $json
248 echo $json;
249 } else {
250 // API handles its own clickjacking protection.
251 // Note, that $wgBreakFrames will still override $wgApiFrameOptions for format mode.
252 $out->allowClickjacking();
253 $out->output();
255 } else {
256 // For non-HTML output, clear all errors that might have been
257 // displayed if display_errors=On
258 ob_clean();
260 echo $this->getBuffer();
265 * Append text to the output buffer.
266 * @param string $text
268 public function printText( $text ) {
269 $this->mBuffer .= $text;
273 * Get the contents of the buffer.
274 * @return string
276 public function getBuffer() {
277 return $this->mBuffer;
280 public function getAllowedParams() {
281 $ret = [];
282 if ( $this->getIsHtml() ) {
283 $ret['wrappedhtml'] = [
284 ApiBase::PARAM_DFLT => false,
285 ApiBase::PARAM_HELP_MSG => 'apihelp-format-param-wrappedhtml',
289 return $ret;
292 protected function getExamplesMessages() {
293 return [
294 'action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName()
295 => [ 'apihelp-format-example-generic', $this->getFormat() ]
299 public function getHelpUrls() {
300 return 'https://www.mediawiki.org/wiki/API:Data_formats';
303 /************************************************************************//**
304 * @name Deprecated
305 * @{
309 * Specify whether or not sequences like &amp;quot; should be unescaped
310 * to &quot; . This should only be set to true for the help message
311 * when rendered in the default (xmlfm) format. This is a temporary
312 * special-case fix that should be removed once the help has been
313 * reworked to use a fully HTML interface.
315 * @deprecated since 1.25
316 * @param bool $b Whether or not ampersands should be escaped.
318 public function setUnescapeAmps( $b ) {
319 wfDeprecated( __METHOD__, '1.25' );
320 $this->mUnescapeAmps = $b;
324 * Whether this formatter can format the help message in a nice way.
325 * By default, this returns the same as getIsHtml().
326 * When action=help is set explicitly, the help will always be shown
327 * @deprecated since 1.25
328 * @return bool
330 public function getWantsHelp() {
331 wfDeprecated( __METHOD__, '1.25' );
332 return $this->getIsHtml();
336 * Sets whether the pretty-printer should format *bold*
337 * @deprecated since 1.25
338 * @param bool $help
340 public function setHelp( $help = true ) {
341 wfDeprecated( __METHOD__, '1.25' );
342 $this->mHelp = $help;
346 * Pretty-print various elements in HTML format, such as xml tags and
347 * URLs. This method also escapes characters like <
348 * @deprecated since 1.25
349 * @param string $text
350 * @return string
352 protected function formatHTML( $text ) {
353 wfDeprecated( __METHOD__, '1.25' );
355 // Escape everything first for full coverage
356 $text = htmlspecialchars( $text );
358 if ( $this->mFormat === 'XML' ) {
359 // encode all comments or tags as safe blue strings
360 $text = str_replace( '&lt;', '<span style="color:blue;">&lt;', $text );
361 $text = str_replace( '&gt;', '&gt;</span>', $text );
364 // identify requests to api.php
365 $text = preg_replace( '#^(\s*)(api\.php\?[^ <\n\t]+)$#m', '\1<a href="\2">\2</a>', $text );
366 if ( $this->mHelp ) {
367 // make lines inside * bold
368 $text = preg_replace( '#^(\s*)(\*[^<>\n]+\*)(\s*)$#m', '$1<b>$2</b>$3', $text );
371 // Armor links (bug 61362)
372 $masked = [];
373 $text = preg_replace_callback( '#<a .*?</a>#', function ( $matches ) use ( &$masked ) {
374 $sha = sha1( $matches[0] );
375 $masked[$sha] = $matches[0];
376 return "<$sha>";
377 }, $text );
379 // identify URLs
380 $protos = wfUrlProtocolsWithoutProtRel();
381 // This regex hacks around bug 13218 (&quot; included in the URL)
382 $text = preg_replace(
383 "#(((?i)$protos).*?)(&quot;)?([ \\'\"<>\n]|&lt;|&gt;|&quot;)#",
384 '<a href="\\1">\\1</a>\\3\\4',
385 $text
388 // Unarmor links
389 $text = preg_replace_callback( '#<([0-9a-f]{40})>#', function ( $matches ) use ( &$masked ) {
390 $sha = $matches[1];
391 return isset( $masked[$sha] ) ? $masked[$sha] : $matches[0];
392 }, $text );
395 * Temporary fix for bad links in help messages. As a special case,
396 * XML-escaped metachars are de-escaped one level in the help message
397 * for legibility. Should be removed once we have completed a fully-HTML
398 * version of the help message.
400 if ( $this->mUnescapeAmps ) {
401 $text = preg_replace( '/&amp;(amp|quot|lt|gt);/', '&\1;', $text );
404 return $text;
408 * @see ApiBase::getDescription
409 * @deprecated since 1.25
411 public function getDescription() {
412 return $this->getIsHtml() ? ' (pretty-print in HTML)' : '';
416 * Set the flag to buffer the result instead of printing it.
417 * @deprecated since 1.25, output is always buffered
418 * @param bool $value
420 public function setBufferResult( $value ) {
424 * Formerly indicated whether the formatter needed metadata from ApiResult.
426 * ApiResult previously (indirectly) used this to decide whether to add
427 * metadata or to ignore calls to metadata-setting methods, which
428 * unfortunately made several methods that should have been static have to
429 * be dynamic instead. Now ApiResult always stores metadata and formatters
430 * are required to ignore it or filter it out.
432 * @deprecated since 1.25
433 * @return bool Always true
435 public function getNeedsRawData() {
436 wfDeprecated( __METHOD__, '1.25' );
437 return true;
440 /**@}*/
444 * For really cool vim folding this needs to be at the end:
445 * vim: foldmarker=@{,@} foldmethod=marker