Revert "selenium: add new message banner test to user spec"
[lhc/web/wiklou.git] / includes / api / ApiFormatBase.php
1 <?php
2 /**
3 *
4 *
5 * Created on Sep 19, 2006
6 *
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
8 *
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.
13 *
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.
18 *
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
23 *
24 * @file
25 */
26
27 /**
28 * This is the abstract base class for API formatters.
29 *
30 * @ingroup API
31 */
32 abstract class ApiFormatBase extends ApiBase {
33 private $mIsHtml, $mFormat;
34 private $mBuffer, $mDisabled = false;
35 private $mIsWrappedHtml = false;
36 private $mHttpStatus = false;
37 protected $mForceDefaultParams = false;
38
39 /**
40 * If $format ends with 'fm', pretty-print the output in HTML.
41 * @param ApiMain $main
42 * @param string $format Format name
43 */
44 public function __construct( ApiMain $main, $format ) {
45 parent::__construct( $main, $format );
46
47 $this->mIsHtml = ( substr( $format, -2, 2 ) === 'fm' ); // ends with 'fm'
48 if ( $this->mIsHtml ) {
49 $this->mFormat = substr( $format, 0, -2 ); // remove ending 'fm'
50 $this->mIsWrappedHtml = $this->getMain()->getCheck( 'wrappedhtml' );
51 } else {
52 $this->mFormat = $format;
53 }
54 $this->mFormat = strtoupper( $this->mFormat );
55 }
56
57 /**
58 * Overriding class returns the MIME type that should be sent to the client.
59 *
60 * When getIsHtml() returns true, the return value here is used for syntax
61 * highlighting but the client sees text/html.
62 *
63 * @return string
64 */
65 abstract public function getMimeType();
66
67 /**
68 * Return a filename for this module's output.
69 * @note If $this->getIsWrappedHtml() || $this->getIsHtml(), you'll very
70 * likely want to fall back to this class's version.
71 * @since 1.27
72 * @return string Generally this should be "api-result.$ext", and must be
73 * encoded for inclusion in a Content-Disposition header's filename parameter.
74 */
75 public function getFilename() {
76 if ( $this->getIsWrappedHtml() ) {
77 return 'api-result-wrapped.json';
78 } elseif ( $this->getIsHtml() ) {
79 return 'api-result.html';
80 } else {
81 $exts = MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer()
82 ->getExtensionsForType( $this->getMimeType() );
83 $ext = $exts ? strtok( $exts, ' ' ) : strtolower( $this->mFormat );
84 return "api-result.$ext";
85 }
86 }
87
88 /**
89 * Get the internal format name
90 * @return string
91 */
92 public function getFormat() {
93 return $this->mFormat;
94 }
95
96 /**
97 * Returns true when the HTML pretty-printer should be used.
98 * The default implementation assumes that formats ending with 'fm'
99 * should be formatted in HTML.
100 * @return bool
101 */
102 public function getIsHtml() {
103 return $this->mIsHtml;
104 }
105
106 /**
107 * Returns true when the special wrapped mode is enabled.
108 * @since 1.27
109 * @return bool
110 */
111 protected function getIsWrappedHtml() {
112 return $this->mIsWrappedHtml;
113 }
114
115 /**
116 * Disable the formatter.
117 *
118 * This causes calls to initPrinter() and closePrinter() to be ignored.
119 */
120 public function disable() {
121 $this->mDisabled = true;
122 }
123
124 /**
125 * Whether the printer is disabled
126 * @return bool
127 */
128 public function isDisabled() {
129 return $this->mDisabled;
130 }
131
132 /**
133 * Whether this formatter can handle printing API errors.
134 *
135 * If this returns false, then on API errors the default printer will be
136 * instantiated.
137 * @since 1.23
138 * @return bool
139 */
140 public function canPrintErrors() {
141 return true;
142 }
143
144 /**
145 * Ignore request parameters, force a default.
146 *
147 * Used as a fallback if errors are being thrown.
148 * @since 1.26
149 */
150 public function forceDefaultParams() {
151 $this->mForceDefaultParams = true;
152 }
153
154 /**
155 * Overridden to honor $this->forceDefaultParams(), if applicable
156 * @inheritDoc
157 * @since 1.26
158 */
159 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
160 if ( !$this->mForceDefaultParams ) {
161 return parent::getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
162 }
163
164 if ( !is_array( $paramSettings ) ) {
165 return $paramSettings;
166 } elseif ( isset( $paramSettings[self::PARAM_DFLT] ) ) {
167 return $paramSettings[self::PARAM_DFLT];
168 } else {
169 return null;
170 }
171 }
172
173 /**
174 * Set the HTTP status code to be used for the response
175 * @since 1.29
176 * @param int $code
177 */
178 public function setHttpStatus( $code ) {
179 if ( $this->mDisabled ) {
180 return;
181 }
182
183 if ( $this->getIsHtml() ) {
184 $this->mHttpStatus = $code;
185 } else {
186 $this->getMain()->getRequest()->response()->statusHeader( $code );
187 }
188 }
189
190 /**
191 * Initialize the printer function and prepare the output headers.
192 * @param bool $unused Always false since 1.25
193 */
194 public function initPrinter( $unused = false ) {
195 if ( $this->mDisabled ) {
196 return;
197 }
198
199 $mime = $this->getIsWrappedHtml()
200 ? 'text/mediawiki-api-prettyprint-wrapped'
201 : ( $this->getIsHtml() ? 'text/html' : $this->getMimeType() );
202
203 // Some printers (ex. Feed) do their own header settings,
204 // in which case $mime will be set to null
205 if ( $mime === null ) {
206 return; // skip any initialization
207 }
208
209 $this->getMain()->getRequest()->response()->header( "Content-Type: $mime; charset=utf-8" );
210
211 // Set X-Frame-Options API results (T41180)
212 $apiFrameOptions = $this->getConfig()->get( 'ApiFrameOptions' );
213 if ( $apiFrameOptions ) {
214 $this->getMain()->getRequest()->response()->header( "X-Frame-Options: $apiFrameOptions" );
215 }
216
217 // Set a Content-Disposition header so something downloading an API
218 // response uses a halfway-sensible filename (T128209).
219 $filename = $this->getFilename();
220 $this->getMain()->getRequest()->response()->header(
221 "Content-Disposition: inline; filename=\"{$filename}\""
222 );
223 }
224
225 /**
226 * Finish printing and output buffered data.
227 */
228 public function closePrinter() {
229 if ( $this->mDisabled ) {
230 return;
231 }
232
233 $mime = $this->getMimeType();
234 if ( $this->getIsHtml() && $mime !== null ) {
235 $format = $this->getFormat();
236 $lcformat = strtolower( $format );
237 $result = $this->getBuffer();
238
239 $context = new DerivativeContext( $this->getMain() );
240 $context->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'apioutput' ) );
241 $context->setTitle( SpecialPage::getTitleFor( 'ApiHelp' ) );
242 $out = new OutputPage( $context );
243 $context->setOutput( $out );
244
245 $out->addModuleStyles( 'mediawiki.apipretty' );
246 $out->setPageTitle( $context->msg( 'api-format-title' ) );
247
248 if ( !$this->getIsWrappedHtml() ) {
249 // When the format without suffix 'fm' is defined, there is a non-html version
250 if ( $this->getMain()->getModuleManager()->isDefined( $lcformat, 'format' ) ) {
251 if ( !$this->getRequest()->wasPosted() ) {
252 $nonHtmlUrl = strtok( $this->getRequest()->getFullRequestURL(), '?' )
253 . '?' . $this->getRequest()->appendQueryValue( 'format', $lcformat );
254 $msg = $context->msg( 'api-format-prettyprint-header-hyperlinked' )
255 ->params( $format, $lcformat, $nonHtmlUrl );
256 } else {
257 $msg = $context->msg( 'api-format-prettyprint-header' )->params( $format, $lcformat );
258 }
259 } else {
260 $msg = $context->msg( 'api-format-prettyprint-header-only-html' )->params( $format );
261 }
262
263 $header = $msg->parseAsBlock();
264 $out->addHTML(
265 Html::rawElement( 'div', [ 'class' => 'api-pretty-header' ],
266 ApiHelp::fixHelpLinks( $header )
267 )
268 );
269
270 if ( $this->mHttpStatus && $this->mHttpStatus !== 200 ) {
271 $out->addHTML(
272 Html::rawElement( 'div', [ 'class' => 'api-pretty-header api-pretty-status' ],
273 $this->msg(
274 'api-format-prettyprint-status',
275 $this->mHttpStatus,
276 HttpStatus::getMessage( $this->mHttpStatus )
277 )->parse()
278 )
279 );
280 }
281 }
282
283 if ( Hooks::run( 'ApiFormatHighlight', [ $context, $result, $mime, $format ] ) ) {
284 $out->addHTML(
285 Html::element( 'pre', [ 'class' => 'api-pretty-content' ], $result )
286 );
287 }
288
289 if ( $this->getIsWrappedHtml() ) {
290 // This is a special output mode mainly intended for ApiSandbox use
291 $time = microtime( true ) - $this->getConfig()->get( 'RequestTime' );
292 $json = FormatJson::encode(
293 [
294 'status' => (int)( $this->mHttpStatus ?: 200 ),
295 'statustext' => HttpStatus::getMessage( $this->mHttpStatus ?: 200 ),
296 'html' => $out->getHTML(),
297 'modules' => array_values( array_unique( array_merge(
298 $out->getModules(),
299 $out->getModuleScripts(),
300 $out->getModuleStyles()
301 ) ) ),
302 'continue' => $this->getResult()->getResultData( 'continue' ),
303 'time' => round( $time * 1000 ),
304 ],
305 false, FormatJson::ALL_OK
306 );
307
308 // T68776: wfMangleFlashPolicy() is needed to avoid a nasty bug in
309 // Flash, but what it does isn't friendly for the API, so we need to
310 // work around it.
311 if ( preg_match( '/\<\s*cross-domain-policy\s*\>/i', $json ) ) {
312 $json = preg_replace(
313 '/\<(\s*cross-domain-policy\s*)\>/i', '\\u003C$1\\u003E', $json
314 );
315 }
316
317 echo $json;
318 } else {
319 // API handles its own clickjacking protection.
320 // Note, that $wgBreakFrames will still override $wgApiFrameOptions for format mode.
321 $out->allowClickjacking();
322 $out->output();
323 }
324 } else {
325 // For non-HTML output, clear all errors that might have been
326 // displayed if display_errors=On
327 ob_clean();
328
329 echo $this->getBuffer();
330 }
331 }
332
333 /**
334 * Append text to the output buffer.
335 * @param string $text
336 */
337 public function printText( $text ) {
338 $this->mBuffer .= $text;
339 }
340
341 /**
342 * Get the contents of the buffer.
343 * @return string
344 */
345 public function getBuffer() {
346 return $this->mBuffer;
347 }
348
349 public function getAllowedParams() {
350 $ret = [];
351 if ( $this->getIsHtml() ) {
352 $ret['wrappedhtml'] = [
353 ApiBase::PARAM_DFLT => false,
354 ApiBase::PARAM_HELP_MSG => 'apihelp-format-param-wrappedhtml',
355
356 ];
357 }
358 return $ret;
359 }
360
361 protected function getExamplesMessages() {
362 return [
363 'action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName()
364 => [ 'apihelp-format-example-generic', $this->getFormat() ]
365 ];
366 }
367
368 public function getHelpUrls() {
369 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Data_formats';
370 }
371
372 }
373
374 /**
375 * For really cool vim folding this needs to be at the end:
376 * vim: foldmarker=@{,@} foldmethod=marker
377 */