Merge "Move up devunt's name to Developers"
[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 'continue' => $this->getResult()->getResultData( 'continue' ),
235 'time' => round( $time * 1000 ),
236 ],
237 false, FormatJson::ALL_OK
238 );
239
240 // Bug 66776: wfMangleFlashPolicy() is needed to avoid a nasty bug in
241 // Flash, but what it does isn't friendly for the API, so we need to
242 // work around it.
243 if ( preg_match( '/\<\s*cross-domain-policy\s*\>/i', $json ) ) {
244 $json = preg_replace(
245 '/\<(\s*cross-domain-policy\s*)\>/i', '\\u003C$1\\u003E', $json
246 );
247 }
248
249 echo $json;
250 } else {
251 // API handles its own clickjacking protection.
252 // Note, that $wgBreakFrames will still override $wgApiFrameOptions for format mode.
253 $out->allowClickjacking();
254 $out->output();
255 }
256 } else {
257 // For non-HTML output, clear all errors that might have been
258 // displayed if display_errors=On
259 ob_clean();
260
261 echo $this->getBuffer();
262 }
263 }
264
265 /**
266 * Append text to the output buffer.
267 * @param string $text
268 */
269 public function printText( $text ) {
270 $this->mBuffer .= $text;
271 }
272
273 /**
274 * Get the contents of the buffer.
275 * @return string
276 */
277 public function getBuffer() {
278 return $this->mBuffer;
279 }
280
281 public function getAllowedParams() {
282 $ret = [];
283 if ( $this->getIsHtml() ) {
284 $ret['wrappedhtml'] = [
285 ApiBase::PARAM_DFLT => false,
286 ApiBase::PARAM_HELP_MSG => 'apihelp-format-param-wrappedhtml',
287
288 ];
289 }
290 return $ret;
291 }
292
293 protected function getExamplesMessages() {
294 return [
295 'action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName()
296 => [ 'apihelp-format-example-generic', $this->getFormat() ]
297 ];
298 }
299
300 public function getHelpUrls() {
301 return 'https://www.mediawiki.org/wiki/API:Data_formats';
302 }
303
304 }
305
306 /**
307 * For really cool vim folding this needs to be at the end:
308 * vim: foldmarker=@{,@} foldmethod=marker
309 */