Merge "Add WatchedItemIntegrationTest"
[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, $mUnescapeAmps, $mHelp;
34 private $mBuffer, $mDisabled = false;
35 private $mIsWrappedHtml = false;
36 protected $mForceDefaultParams = false;
37
38 /**
39 * If $format ends with 'fm', pretty-print the output in HTML.
40 * @param ApiMain $main
41 * @param string $format Format name
42 */
43 public function __construct( ApiMain $main, $format ) {
44 parent::__construct( $main, $format );
45
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;
52 }
53 $this->mFormat = strtoupper( $this->mFormat );
54 }
55
56 /**
57 * Overriding class returns the MIME type that should be sent to the client.
58 *
59 * When getIsHtml() returns true, the return value here is used for syntax
60 * highlighting but the client sees text/html.
61 *
62 * @return string
63 */
64 abstract public function getMimeType();
65
66 /**
67 * Get the internal format name
68 * @return string
69 */
70 public function getFormat() {
71 return $this->mFormat;
72 }
73
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
79 */
80 public function getIsHtml() {
81 return $this->mIsHtml;
82 }
83
84 /**
85 * Returns true when the special wrapped mode is enabled.
86 * @since 1.27
87 * @return bool
88 */
89 protected function getIsWrappedHtml() {
90 return $this->mIsWrappedHtml;
91 }
92
93 /**
94 * Disable the formatter.
95 *
96 * This causes calls to initPrinter() and closePrinter() to be ignored.
97 */
98 public function disable() {
99 $this->mDisabled = true;
100 }
101
102 /**
103 * Whether the printer is disabled
104 * @return bool
105 */
106 public function isDisabled() {
107 return $this->mDisabled;
108 }
109
110 /**
111 * Whether this formatter can handle printing API errors.
112 *
113 * If this returns false, then on API errors the default printer will be
114 * instantiated.
115 * @since 1.23
116 * @return bool
117 */
118 public function canPrintErrors() {
119 return true;
120 }
121
122 /**
123 * Ignore request parameters, force a default.
124 *
125 * Used as a fallback if errors are being thrown.
126 * @since 1.26
127 */
128 public function forceDefaultParams() {
129 $this->mForceDefaultParams = true;
130 }
131
132 /**
133 * Overridden to honor $this->forceDefaultParams(), if applicable
134 * @since 1.26
135 */
136 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
137 if ( !$this->mForceDefaultParams ) {
138 return parent::getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
139 }
140
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;
147 }
148 }
149
150 /**
151 * Initialize the printer function and prepare the output headers.
152 * @param bool $unused Always false since 1.25
153 */
154 public function initPrinter( $unused = false ) {
155 if ( $this->mDisabled ) {
156 return;
157 }
158
159 $mime = $this->getIsWrappedHtml()
160 ? 'text/mediawiki-api-prettyprint-wrapped'
161 : ( $this->getIsHtml() ? 'text/html' : $this->getMimeType() );
162
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
167 }
168
169 $this->getMain()->getRequest()->response()->header( "Content-Type: $mime; charset=utf-8" );
170
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" );
175 }
176 }
177
178 /**
179 * Finish printing and output buffered data.
180 */
181 public function closePrinter() {
182 if ( $this->mDisabled ) {
183 return;
184 }
185
186 $mime = $this->getMimeType();
187 if ( $this->getIsHtml() && $mime !== null ) {
188 $format = $this->getFormat();
189 $lcformat = strtolower( $format );
190 $result = $this->getBuffer();
191
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 );
197
198 $out->addModuleStyles( 'mediawiki.apipretty' );
199 $out->setPageTitle( $context->msg( 'api-format-title' ) );
200
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 );
207 }
208
209 $header = $msg->parseAsBlock();
210 $out->addHTML(
211 Html::rawElement( 'div', [ 'class' => 'api-pretty-header' ],
212 ApiHelp::fixHelpLinks( $header )
213 )
214 );
215 }
216
217 if ( Hooks::run( 'ApiFormatHighlight', [ $context, $result, $mime, $format ] ) ) {
218 $out->addHTML(
219 Html::element( 'pre', [ 'class' => 'api-pretty-content' ], $result )
220 );
221 }
222
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(
227 [
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 ),
235 ],
236 false, FormatJson::ALL_OK
237 );
238
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
245 );
246 }
247
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();
254 }
255 } else {
256 // For non-HTML output, clear all errors that might have been
257 // displayed if display_errors=On
258 ob_clean();
259
260 echo $this->getBuffer();
261 }
262 }
263
264 /**
265 * Append text to the output buffer.
266 * @param string $text
267 */
268 public function printText( $text ) {
269 $this->mBuffer .= $text;
270 }
271
272 /**
273 * Get the contents of the buffer.
274 * @return string
275 */
276 public function getBuffer() {
277 return $this->mBuffer;
278 }
279
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',
286
287 ];
288 }
289 return $ret;
290 }
291
292 protected function getExamplesMessages() {
293 return [
294 'action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName()
295 => [ 'apihelp-format-example-generic', $this->getFormat() ]
296 ];
297 }
298
299 public function getHelpUrls() {
300 return 'https://www.mediawiki.org/wiki/API:Data_formats';
301 }
302
303 /************************************************************************//**
304 * @name Deprecated
305 * @{
306 */
307
308 /**
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.
314 *
315 * @deprecated since 1.25
316 * @param bool $b Whether or not ampersands should be escaped.
317 */
318 public function setUnescapeAmps( $b ) {
319 wfDeprecated( __METHOD__, '1.25' );
320 $this->mUnescapeAmps = $b;
321 }
322
323 /**
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
329 */
330 public function getWantsHelp() {
331 wfDeprecated( __METHOD__, '1.25' );
332 return $this->getIsHtml();
333 }
334
335 /**
336 * Sets whether the pretty-printer should format *bold*
337 * @deprecated since 1.25
338 * @param bool $help
339 */
340 public function setHelp( $help = true ) {
341 wfDeprecated( __METHOD__, '1.25' );
342 $this->mHelp = $help;
343 }
344
345 /**
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
351 */
352 protected function formatHTML( $text ) {
353 wfDeprecated( __METHOD__, '1.25' );
354
355 // Escape everything first for full coverage
356 $text = htmlspecialchars( $text );
357
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 );
362 }
363
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 );
369 }
370
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 );
378
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
386 );
387
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 );
393
394 /**
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.
399 */
400 if ( $this->mUnescapeAmps ) {
401 $text = preg_replace( '/&amp;(amp|quot|lt|gt);/', '&\1;', $text );
402 }
403
404 return $text;
405 }
406
407 /**
408 * @see ApiBase::getDescription
409 * @deprecated since 1.25
410 */
411 public function getDescription() {
412 return $this->getIsHtml() ? ' (pretty-print in HTML)' : '';
413 }
414
415 /**
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
419 */
420 public function setBufferResult( $value ) {
421 }
422
423 /**
424 * Formerly indicated whether the formatter needed metadata from ApiResult.
425 *
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.
431 *
432 * @deprecated since 1.25
433 * @return bool Always true
434 */
435 public function getNeedsRawData() {
436 wfDeprecated( __METHOD__, '1.25' );
437 return true;
438 }
439
440 /**@}*/
441 }
442
443 /**
444 * For really cool vim folding this needs to be at the end:
445 * vim: foldmarker=@{,@} foldmethod=marker
446 */