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