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