Debian Codegraph @

includes/api/ApiFormatBase.php

raw symbols SCIP
1 <?php
2 /**
3 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 namespace MediaWiki\Api;
24
25 use HttpStatus;
26 use MediaWiki\Context\DerivativeContext;
27 use MediaWiki\Html\Html;
28 use MediaWiki\Json\FormatJson;
29 use MediaWiki\MainConfigNames;
30 use MediaWiki\MediaWikiServices;
31 use MediaWiki\Output\OutputPage;
32 use MediaWiki\ResourceLoader as RL;
33 use MediaWiki\SpecialPage\SpecialPage;
34 use Wikimedia\ParamValidator\ParamValidator;
35
36 /**
37 * This is the abstract base class for API formatters.
38 *
39 * @ingroup API
40 */
41 abstract class ApiFormatBase extends ApiBase {
42 private bool $mIsHtml;
43 private string $mFormat;
44 private string $mBuffer = '';
45 private bool $mDisabled = false;
46 /** @var bool */
47 private $mIsWrappedHtml = false;
48 /** @var int|false */
49 private $mHttpStatus = false;
50 /** @var bool */
51 protected $mForceDefaultParams = false;
52
53 /**
54 * If $format ends with 'fm', pretty-print the output in HTML.
55 *
56 * @param ApiMain $main
57 * @param string $format Format name
58 */
59 public function __construct( ApiMain $main, string $format ) {
60 parent::__construct( $main, $format );
61
62 $this->mIsHtml = str_ends_with( $format, 'fm' );
63 if ( $this->mIsHtml ) {
64 $this->mFormat = substr( $format, 0, -2 ); // remove ending 'fm'
65 $this->mIsWrappedHtml = $this->getMain()->getCheck( 'wrappedhtml' );
66 } else {
67 $this->mFormat = $format;
68 }
69 $this->mFormat = strtoupper( $this->mFormat );
70 }
71
72 /**
73 * Overriding class returns the MIME type that should be sent to the client.
74 *
75 * When getIsHtml() returns true, the return value here is used for syntax
76 * highlighting, but the client sees text/html.
77 *
78 * @return string|null
79 */
80 abstract public function getMimeType();
81
82 /**
83 * Return a filename for this module's output.
84 *
85 * @note If $this->getIsWrappedHtml() || $this->getIsHtml(), you'll very
86 * likely want to fall back to this class's version.
87 * @since 1.27
88 * @return string Generally, this should be "api-result.$ext"
89 */
90 public function getFilename() {
91 if ( $this->getIsWrappedHtml() ) {
92 return 'api-result-wrapped.json';
93 }
94
95 if ( $this->getIsHtml() ) {
96 return 'api-result.html';
97 }
98
99 $mimeAnalyzer = MediaWikiServices::getInstance()->getMimeAnalyzer();
100 $ext = $mimeAnalyzer->getExtensionFromMimeTypeOrNull( $this->getMimeType() )
101 ?? strtolower( $this->mFormat );
102 return "api-result.$ext";
103 }
104
105 /**
106 * Get the internal format name
107 *
108 * @return string
109 */
110 public function getFormat() {
111 return $this->mFormat;
112 }
113
114 /**
115 * Returns true when the HTML pretty-printer should be used.
116 * The default implementation assumes that formats ending with 'fm' should be formatted in HTML.
117 *
118 * @return bool
119 */
120 public function getIsHtml() {
121 return $this->mIsHtml;
122 }
123
124 /**
125 * Returns true when the special-wrapped mode is enabled.
126 *
127 * @since 1.27
128 * @return bool
129 */
130 protected function getIsWrappedHtml() {
131 return $this->mIsWrappedHtml;
132 }
133
134 /**
135 * Disable the formatter.
136 *
137 * This causes calls to initPrinter() and closePrinter() to be ignored.
138 */
139 public function disable() {
140 $this->mDisabled = true;
141 }
142
143 /**
144 * Whether the printer is disabled.
145 *
146 * @return bool
147 */
148 public function isDisabled() {
149 return $this->mDisabled;
150 }
151
152 /**
153 * Whether this formatter can handle printing API errors.
154 *
155 * If this returns false, then when API errors occur, the default printer will be instantiated.
156 * @since 1.23
157 * @return bool
158 */
159 public function canPrintErrors() {
160 return true;
161 }
162
163 /**
164 * Ignore request parameters, force a default.
165 *
166 * Used as a fallback if errors are being thrown.
167 *
168 * @since 1.26
169 */
170 public function forceDefaultParams() {
171 $this->mForceDefaultParams = true;
172 }
173
174 /**
175 * Overridden to honor $this->forceDefaultParams(), if applicable
176 * @inheritDoc
177 * @since 1.26
178 */
179 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
180 if ( !$this->mForceDefaultParams ) {
181 return parent::getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
182 }
183
184 if ( !is_array( $paramSettings ) ) {
185 return $paramSettings;
186 }
187
188 return $paramSettings[ParamValidator::PARAM_DEFAULT] ?? null;
189 }
190
191 /**
192 * Set the HTTP status code to be used for the response
193 * @since 1.29
194 * @param int $code
195 */
196 public function setHttpStatus( $code ) {
197 if ( $this->mDisabled ) {
198 return;
199 }
200
201 if ( $this->getIsHtml() ) {
202 $this->mHttpStatus = $code;
203 } else {
204 $this->getMain()->getRequest()->response()->statusHeader( $code );
205 }
206 }
207
208 /**
209 * Initialize the printer function and prepare the output headers.
210 * @param bool $unused Always false since 1.25
211 */
212 public function initPrinter( $unused = false ) {
213 if ( $this->mDisabled ) {
214 return;
215 }
216
217 if ( $this->getIsHtml() && $this->getMain()->getCacheMode() === 'public' ) {
218 // The HTML may contain user secrets! T354045
219 $this->getMain()->setCacheMode( 'anon-public-user-private' );
220 }
221
222 $mime = $this->getIsWrappedHtml()
223 ? 'text/mediawiki-api-prettyprint-wrapped'
224 : ( $this->getIsHtml() ? 'text/html' : $this->getMimeType() );
225
226 // Some printers (ex. Feed) do their own header settings,
227 // in which case $mime will be set to null
228 if ( $mime === null ) {
229 return; // skip any initialization
230 }
231
232 $this->getMain()->getRequest()->response()->header( "Content-Type: $mime; charset=utf-8" );
233
234 // Set X-Frame-Options API results (T41180)
235 $apiFrameOptions = $this->getConfig()->get( MainConfigNames::ApiFrameOptions );
236 if ( $apiFrameOptions ) {
237 $this->getMain()->getRequest()->response()->header( "X-Frame-Options: $apiFrameOptions" );
238 }
239
240 // Set a Content-Disposition header so something downloading an API
241 // response uses a halfway-sensible filename (T128209).
242 $header = 'Content-Disposition: inline';
243 $filename = $this->getFilename();
244 $compatFilename = mb_convert_encoding( $filename, 'ISO-8859-1' );
245 if ( preg_match( '/^[0-9a-zA-Z!#$%&\'*+\-.^_`|~]+$/', $compatFilename ) ) {
246 $header .= '; filename=' . $compatFilename;
247 } else {
248 $header .= '; filename="'
249 . preg_replace( '/([\0-\x1f"\x5c\x7f])/', '\\\\$1', $compatFilename ) . '"';
250 }
251 if ( $compatFilename !== $filename ) {
252 $value = "UTF-8''" . rawurlencode( $filename );
253 // rawurlencode() encodes more characters than RFC 5987 specifies. Unescape the ones it allows.
254 $value = strtr( $value, [
255 '%21' => '!', '%23' => '#', '%24' => '$', '%26' => '&', '%2B' => '+', '%5E' => '^',
256 '%60' => '`', '%7C' => '|',
257 ] );
258 $header .= '; filename*=' . $value;
259 }
260 $this->getMain()->getRequest()->response()->header( $header );
261 }
262
263 /**
264 * Finish printing and output buffered data.
265 */
266 public function closePrinter() {
267 if ( $this->mDisabled ) {
268 return;
269 }
270
271 $mime = $this->getMimeType();
272 if ( $this->getIsHtml() && $mime !== null ) {
273 $format = $this->getFormat();
274 $lcformat = strtolower( $format );
275 $result = $this->getBuffer();
276
277 $context = new DerivativeContext( $this->getMain() );
278 $skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
279 $context->setSkin( $skinFactory->makeSkin( 'apioutput' ) );
280 $context->setTitle( SpecialPage::getTitleFor( 'ApiHelp' ) );
281 $out = new OutputPage( $context );
282 $context->setOutput( $out );
283
284 $out->setRobotPolicy( 'noindex,nofollow' );
285 $out->disallowUserJs();
286 $out->reduceAllowedModules( RL\Module::TYPE_SCRIPTS, RL\Module::ORIGIN_NONE );
287 $out->addModuleStyles( 'mediawiki.apipretty' );
288 $out->setPageTitleMsg( $context->msg( 'api-format-title' ) );
289
290 if ( !$this->getIsWrappedHtml() ) {
291 // When the format without suffix 'fm' is defined, there is a non-html version
292 if ( $this->getMain()->getModuleManager()->isDefined( $lcformat, 'format' ) ) {
293 if ( !$this->getRequest()->wasPosted() ) {
294 $nonHtmlUrl = strtok( $this->getRequest()->getFullRequestURL(), '?' )
295 . '?' . $this->getRequest()->appendQueryValue( 'format', $lcformat );
296 $msg = $context->msg( 'api-format-prettyprint-header-hyperlinked' )
297 ->params( $format, $lcformat, $nonHtmlUrl );
298 } else {
299 $msg = $context->msg( 'api-format-prettyprint-header' )->params( $format, $lcformat );
300 }
301 } else {
302 $msg = $context->msg( 'api-format-prettyprint-header-only-html' )->params( $format );
303 }
304
305 $header = $msg->parseAsBlock();
306 $out->addHTML(
307 Html::rawElement( 'div', [ 'class' => 'api-pretty-header' ],
308 ApiHelp::fixHelpLinks( $header )
309 )
310 );
311
312 if ( $this->mHttpStatus && $this->mHttpStatus !== 200 ) {
313 $out->addHTML(
314 Html::rawElement( 'div', [ 'class' => [ 'api-pretty-header', 'api-pretty-status' ] ],
315 $this->msg(
316 'api-format-prettyprint-status',
317 $this->mHttpStatus,
318 HttpStatus::getMessage( $this->mHttpStatus )
319 )->parse()
320 )
321 );
322 }
323 }
324
325 if ( $this->getHookRunner()->onApiFormatHighlight( $context, $result, $mime, $format ) ) {
326 $out->addHTML(
327 Html::element( 'pre', [ 'class' => 'api-pretty-content' ], $result )
328 );
329 }
330
331 if ( $this->getIsWrappedHtml() ) {
332 // This is a special output mode mainly intended for ApiSandbox use
333 $time = $this->getMain()->getRequest()->getElapsedTime();
334 echo FormatJson::encode(
335 [
336 'status' => (int)( $this->mHttpStatus ?: 200 ),
337 'statustext' => HttpStatus::getMessage( $this->mHttpStatus ?: 200 ),
338 'html' => $out->getHTML(),
339 'modules' => array_values( array_unique( array_merge(
340 $out->getModules(),
341 $out->getModuleStyles()
342 ) ) ),
343 'continue' => $this->getResult()->getResultData( 'continue' ),
344 'time' => round( $time * 1000 ),
345 ],
346 false, FormatJson::ALL_OK
347 );
348 } else {
349 // API handles its own clickjacking protection.
350 // Note: $wgBreakFrames will still override $wgApiFrameOptions for format mode.
351 $out->getMetadata()->setPreventClickjacking( false );
352 $out->output();
353 }
354 } else {
355 // For non-HTML output, clear all errors that might have been
356 // displayed if display_errors=On
357 ob_clean();
358
359 echo $this->getBuffer();
360 }
361 }
362
363 /**
364 * Append text to the output buffer.
365 *
366 * @param string $text
367 */
368 public function printText( $text ) {
369 $this->mBuffer .= $text;
370 }
371
372 /**
373 * Get the contents of the buffer.
374 *
375 * @return string
376 */
377 public function getBuffer() {
378 return $this->mBuffer;
379 }
380
381 public function getAllowedParams() {
382 $ret = [];
383 if ( $this->getIsHtml() ) {
384 $ret['wrappedhtml'] = [
385 ParamValidator::PARAM_DEFAULT => false,
386 ApiBase::PARAM_HELP_MSG => 'apihelp-format-param-wrappedhtml',
387 ];
388 }
389 return $ret;
390 }
391
392 protected function getExamplesMessages() {
393 return [
394 'action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName()
395 => [ 'apihelp-format-example-generic', $this->getFormat() ]
396 ];
397 }
398
399 public function getHelpUrls() {
400 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Data_formats';
401 }
402
403 }
404
405 /**
406 * For really cool vim folding this needs to be at the end:
407 * vim: foldmarker=@{,@} foldmethod=marker
408 */
409
410 /** @deprecated class alias since 1.43 */
411 class_alias( ApiFormatBase::class, 'ApiFormatBase' );