Merge "Linker: Accept LinkTargets in makeCommentLink()"
[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 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 * Get the internal format name
69 * @return string
70 */
71 public function getFormat() {
72 return $this->mFormat;
73 }
74
75 /**
76 * Returns true when the HTML pretty-printer should be used.
77 * The default implementation assumes that formats ending with 'fm'
78 * should be formatted in HTML.
79 * @return bool
80 */
81 public function getIsHtml() {
82 return $this->mIsHtml;
83 }
84
85 /**
86 * Returns true when the special wrapped mode is enabled.
87 * @since 1.27
88 * @return bool
89 */
90 protected function getIsWrappedHtml() {
91 return $this->mIsWrappedHtml;
92 }
93
94 /**
95 * Disable the formatter.
96 *
97 * This causes calls to initPrinter() and closePrinter() to be ignored.
98 */
99 public function disable() {
100 $this->mDisabled = true;
101 }
102
103 /**
104 * Whether the printer is disabled
105 * @return bool
106 */
107 public function isDisabled() {
108 return $this->mDisabled;
109 }
110
111 /**
112 * Whether this formatter can handle printing API errors.
113 *
114 * If this returns false, then on API errors the default printer will be
115 * instantiated.
116 * @since 1.23
117 * @return bool
118 */
119 public function canPrintErrors() {
120 return true;
121 }
122
123 /**
124 * Ignore request parameters, force a default.
125 *
126 * Used as a fallback if errors are being thrown.
127 * @since 1.26
128 */
129 public function forceDefaultParams() {
130 $this->mForceDefaultParams = true;
131 }
132
133 /**
134 * Overridden to honor $this->forceDefaultParams(), if applicable
135 * @inheritDoc
136 * @since 1.26
137 */
138 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
139 if ( !$this->mForceDefaultParams ) {
140 return parent::getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
141 }
142
143 if ( !is_array( $paramSettings ) ) {
144 return $paramSettings;
145 } elseif ( isset( $paramSettings[self::PARAM_DFLT] ) ) {
146 return $paramSettings[self::PARAM_DFLT];
147 } else {
148 return null;
149 }
150 }
151
152 /**
153 * Set the HTTP status code to be used for the response
154 * @since 1.29
155 * @param int $code
156 */
157 public function setHttpStatus( $code ) {
158 if ( $this->mDisabled ) {
159 return;
160 }
161
162 if ( $this->getIsHtml() ) {
163 $this->mHttpStatus = $code;
164 } else {
165 $this->getMain()->getRequest()->response()->statusHeader( $code );
166 }
167 }
168
169 /**
170 * Initialize the printer function and prepare the output headers.
171 * @param bool $unused Always false since 1.25
172 */
173 public function initPrinter( $unused = false ) {
174 if ( $this->mDisabled ) {
175 return;
176 }
177
178 $mime = $this->getIsWrappedHtml()
179 ? 'text/mediawiki-api-prettyprint-wrapped'
180 : ( $this->getIsHtml() ? 'text/html' : $this->getMimeType() );
181
182 // Some printers (ex. Feed) do their own header settings,
183 // in which case $mime will be set to null
184 if ( $mime === null ) {
185 return; // skip any initialization
186 }
187
188 $this->getMain()->getRequest()->response()->header( "Content-Type: $mime; charset=utf-8" );
189
190 // Set X-Frame-Options API results (T41180)
191 $apiFrameOptions = $this->getConfig()->get( 'ApiFrameOptions' );
192 if ( $apiFrameOptions ) {
193 $this->getMain()->getRequest()->response()->header( "X-Frame-Options: $apiFrameOptions" );
194 }
195 }
196
197 /**
198 * Finish printing and output buffered data.
199 */
200 public function closePrinter() {
201 if ( $this->mDisabled ) {
202 return;
203 }
204
205 $mime = $this->getMimeType();
206 if ( $this->getIsHtml() && $mime !== null ) {
207 $format = $this->getFormat();
208 $lcformat = strtolower( $format );
209 $result = $this->getBuffer();
210
211 $context = new DerivativeContext( $this->getMain() );
212 $context->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'apioutput' ) );
213 $context->setTitle( SpecialPage::getTitleFor( 'ApiHelp' ) );
214 $out = new OutputPage( $context );
215 $context->setOutput( $out );
216
217 $out->addModuleStyles( 'mediawiki.apipretty' );
218 $out->setPageTitle( $context->msg( 'api-format-title' ) );
219
220 if ( !$this->getIsWrappedHtml() ) {
221 // When the format without suffix 'fm' is defined, there is a non-html version
222 if ( $this->getMain()->getModuleManager()->isDefined( $lcformat, 'format' ) ) {
223 if ( !$this->getRequest()->wasPosted() ) {
224 $nonHtmlUrl = strtok( $this->getRequest()->getFullRequestURL(), '?' )
225 . '?' . $this->getRequest()->appendQueryValue( 'format', $lcformat );
226 $msg = $context->msg( 'api-format-prettyprint-header-hyperlinked' )
227 ->params( $format, $lcformat, $nonHtmlUrl );
228 } else {
229 $msg = $context->msg( 'api-format-prettyprint-header' )->params( $format, $lcformat );
230 }
231 } else {
232 $msg = $context->msg( 'api-format-prettyprint-header-only-html' )->params( $format );
233 }
234
235 $header = $msg->parseAsBlock();
236 $out->addHTML(
237 Html::rawElement( 'div', [ 'class' => 'api-pretty-header' ],
238 ApiHelp::fixHelpLinks( $header )
239 )
240 );
241
242 if ( $this->mHttpStatus && $this->mHttpStatus !== 200 ) {
243 $out->addHTML(
244 Html::rawElement( 'div', [ 'class' => 'api-pretty-header api-pretty-status' ],
245 $this->msg(
246 'api-format-prettyprint-status',
247 $this->mHttpStatus,
248 HttpStatus::getMessage( $this->mHttpStatus )
249 )->parse()
250 )
251 );
252 }
253 }
254
255 if ( Hooks::run( 'ApiFormatHighlight', [ $context, $result, $mime, $format ] ) ) {
256 $out->addHTML(
257 Html::element( 'pre', [ 'class' => 'api-pretty-content' ], $result )
258 );
259 }
260
261 if ( $this->getIsWrappedHtml() ) {
262 // This is a special output mode mainly intended for ApiSandbox use
263 $time = microtime( true ) - $this->getConfig()->get( 'RequestTime' );
264 $json = FormatJson::encode(
265 [
266 'status' => (int)( $this->mHttpStatus ?: 200 ),
267 'statustext' => HttpStatus::getMessage( $this->mHttpStatus ?: 200 ),
268 'html' => $out->getHTML(),
269 'modules' => array_values( array_unique( array_merge(
270 $out->getModules(),
271 $out->getModuleScripts(),
272 $out->getModuleStyles()
273 ) ) ),
274 'continue' => $this->getResult()->getResultData( 'continue' ),
275 'time' => round( $time * 1000 ),
276 ],
277 false, FormatJson::ALL_OK
278 );
279
280 // T68776: wfMangleFlashPolicy() is needed to avoid a nasty bug in
281 // Flash, but what it does isn't friendly for the API, so we need to
282 // work around it.
283 if ( preg_match( '/\<\s*cross-domain-policy\s*\>/i', $json ) ) {
284 $json = preg_replace(
285 '/\<(\s*cross-domain-policy\s*)\>/i', '\\u003C$1\\u003E', $json
286 );
287 }
288
289 echo $json;
290 } else {
291 // API handles its own clickjacking protection.
292 // Note, that $wgBreakFrames will still override $wgApiFrameOptions for format mode.
293 $out->allowClickjacking();
294 $out->output();
295 }
296 } else {
297 // For non-HTML output, clear all errors that might have been
298 // displayed if display_errors=On
299 ob_clean();
300
301 echo $this->getBuffer();
302 }
303 }
304
305 /**
306 * Append text to the output buffer.
307 * @param string $text
308 */
309 public function printText( $text ) {
310 $this->mBuffer .= $text;
311 }
312
313 /**
314 * Get the contents of the buffer.
315 * @return string
316 */
317 public function getBuffer() {
318 return $this->mBuffer;
319 }
320
321 public function getAllowedParams() {
322 $ret = [];
323 if ( $this->getIsHtml() ) {
324 $ret['wrappedhtml'] = [
325 ApiBase::PARAM_DFLT => false,
326 ApiBase::PARAM_HELP_MSG => 'apihelp-format-param-wrappedhtml',
327
328 ];
329 }
330 return $ret;
331 }
332
333 protected function getExamplesMessages() {
334 return [
335 'action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName()
336 => [ 'apihelp-format-example-generic', $this->getFormat() ]
337 ];
338 }
339
340 public function getHelpUrls() {
341 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Data_formats';
342 }
343
344 }
345
346 /**
347 * For really cool vim folding this needs to be at the end:
348 * vim: foldmarker=@{,@} foldmethod=marker
349 */