Don't check namespace in SpecialWantedtemplates
[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 protected $mForceDefaultParams = false;
36
37 /**
38 * If $format ends with 'fm', pretty-print the output in HTML.
39 * @param ApiMain $main
40 * @param string $format Format name
41 */
42 public function __construct( ApiMain $main, $format ) {
43 parent::__construct( $main, $format );
44
45 $this->mIsHtml = ( substr( $format, -2, 2 ) === 'fm' ); // ends with 'fm'
46 if ( $this->mIsHtml ) {
47 $this->mFormat = substr( $format, 0, -2 ); // remove ending 'fm'
48 } else {
49 $this->mFormat = $format;
50 }
51 $this->mFormat = strtoupper( $this->mFormat );
52 }
53
54 /**
55 * Overriding class returns the MIME type that should be sent to the client.
56 *
57 * When getIsHtml() returns true, the return value here is used for syntax
58 * highlighting but the client sees text/html.
59 *
60 * @return string
61 */
62 abstract public function getMimeType();
63
64 /**
65 * Get the internal format name
66 * @return string
67 */
68 public function getFormat() {
69 return $this->mFormat;
70 }
71
72 /**
73 * Returns true when the HTML pretty-printer should be used.
74 * The default implementation assumes that formats ending with 'fm'
75 * should be formatted in HTML.
76 * @return bool
77 */
78 public function getIsHtml() {
79 return $this->mIsHtml;
80 }
81
82 /**
83 * Disable the formatter.
84 *
85 * This causes calls to initPrinter() and closePrinter() to be ignored.
86 */
87 public function disable() {
88 $this->mDisabled = true;
89 }
90
91 /**
92 * Whether the printer is disabled
93 * @return bool
94 */
95 public function isDisabled() {
96 return $this->mDisabled;
97 }
98
99 /**
100 * Whether this formatter can handle printing API errors.
101 *
102 * If this returns false, then on API errors the default printer will be
103 * instantiated.
104 * @since 1.23
105 * @return bool
106 */
107 public function canPrintErrors() {
108 return true;
109 }
110
111 /**
112 * Ignore request parameters, force a default.
113 *
114 * Used as a fallback if errors are being thrown.
115 * @since 1.26
116 */
117 public function forceDefaultParams() {
118 $this->mForceDefaultParams = true;
119 }
120
121 /**
122 * Overridden to honor $this->forceDefaultParams(), if applicable
123 * @since 1.26
124 */
125 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
126 if ( !$this->mForceDefaultParams ) {
127 return parent::getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
128 }
129
130 if ( !is_array( $paramSettings ) ) {
131 return $paramSettings;
132 } elseif ( isset( $paramSettings[self::PARAM_DFLT] ) ) {
133 return $paramSettings[self::PARAM_DFLT];
134 } else {
135 return null;
136 }
137 }
138
139 /**
140 * Initialize the printer function and prepare the output headers.
141 * @param bool $unused Always false since 1.25
142 */
143 function initPrinter( $unused = false ) {
144 if ( $this->mDisabled ) {
145 return;
146 }
147
148 $mime = $this->getIsHtml() ? 'text/html' : $this->getMimeType();
149
150 // Some printers (ex. Feed) do their own header settings,
151 // in which case $mime will be set to null
152 if ( $mime === null ) {
153 return; // skip any initialization
154 }
155
156 $this->getMain()->getRequest()->response()->header( "Content-Type: $mime; charset=utf-8" );
157
158 //Set X-Frame-Options API results (bug 39180)
159 $apiFrameOptions = $this->getConfig()->get( 'ApiFrameOptions' );
160 if ( $apiFrameOptions ) {
161 $this->getMain()->getRequest()->response()->header( "X-Frame-Options: $apiFrameOptions" );
162 }
163 }
164
165 /**
166 * Finish printing and output buffered data.
167 */
168 public function closePrinter() {
169 if ( $this->mDisabled ) {
170 return;
171 }
172
173 $mime = $this->getMimeType();
174 if ( $this->getIsHtml() && $mime !== null ) {
175 $format = $this->getFormat();
176 $lcformat = strtolower( $format );
177 $result = $this->getBuffer();
178
179 $context = new DerivativeContext( $this->getMain() );
180 $context->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'apioutput' ) );
181 $context->setTitle( SpecialPage::getTitleFor( 'ApiHelp' ) );
182 $out = new OutputPage( $context );
183 $context->setOutput( $out );
184
185 $out->addModules( 'mediawiki.apipretty' );
186 $out->setPageTitle( $context->msg( 'api-format-title' ) );
187
188 // When the format without suffix 'fm' is defined, there is a non-html version
189 if ( $this->getMain()->getModuleManager()->isDefined( $lcformat, 'format' ) ) {
190 $msg = $context->msg( 'api-format-prettyprint-header' )->params( $format, $lcformat );
191 } else {
192 $msg = $context->msg( 'api-format-prettyprint-header-only-html' )->params( $format );
193 }
194
195 $header = $msg->parseAsBlock();
196 $out->addHTML(
197 Html::rawElement( 'div', array( 'class' => 'api-pretty-header' ),
198 ApiHelp::fixHelpLinks( $header )
199 )
200 );
201
202 if ( Hooks::run( 'ApiFormatHighlight', array( $context, $result, $mime, $format ) ) ) {
203 $out->addHTML(
204 Html::element( 'pre', array( 'class' => 'api-pretty-content' ), $result )
205 );
206 }
207
208 // API handles its own clickjacking protection.
209 // Note, that $wgBreakFrames will still override $wgApiFrameOptions for format mode.
210 $out->allowClickJacking();
211 $out->output();
212 } else {
213 // For non-HTML output, clear all errors that might have been
214 // displayed if display_errors=On
215 ob_clean();
216
217 echo $this->getBuffer();
218 }
219 }
220
221 /**
222 * Append text to the output buffer.
223 * @param string $text
224 */
225 public function printText( $text ) {
226 $this->mBuffer .= $text;
227 }
228
229 /**
230 * Get the contents of the buffer.
231 * @return string
232 */
233 public function getBuffer() {
234 return $this->mBuffer;
235 }
236
237 protected function getExamplesMessages() {
238 return array(
239 'action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName()
240 => array( 'apihelp-format-example-generic', $this->getFormat() )
241 );
242 }
243
244 public function getHelpUrls() {
245 return 'https://www.mediawiki.org/wiki/API:Data_formats';
246 }
247
248 /**
249 * To avoid code duplication with the deprecation of dbg, dump, txt, wddx,
250 * and yaml, this method is added to do the necessary work. It should be
251 * removed when those deprecated formats are removed.
252 */
253 protected function markDeprecated() {
254 $fm = $this->getIsHtml() ? 'fm' : '';
255 $name = $this->getModuleName();
256 $this->logFeatureUsage( "format=$name" );
257 $this->setWarning( "format=$name has been deprecated. Please use format=json$fm instead." );
258 }
259
260 /************************************************************************//**
261 * @name Deprecated
262 * @{
263 */
264
265 /**
266 * Specify whether or not sequences like &amp;quot; should be unescaped
267 * to &quot; . This should only be set to true for the help message
268 * when rendered in the default (xmlfm) format. This is a temporary
269 * special-case fix that should be removed once the help has been
270 * reworked to use a fully HTML interface.
271 *
272 * @deprecated since 1.25
273 * @param bool $b Whether or not ampersands should be escaped.
274 */
275 public function setUnescapeAmps( $b ) {
276 wfDeprecated( __METHOD__, '1.25' );
277 $this->mUnescapeAmps = $b;
278 }
279
280 /**
281 * Whether this formatter can format the help message in a nice way.
282 * By default, this returns the same as getIsHtml().
283 * When action=help is set explicitly, the help will always be shown
284 * @deprecated since 1.25
285 * @return bool
286 */
287 public function getWantsHelp() {
288 wfDeprecated( __METHOD__, '1.25' );
289 return $this->getIsHtml();
290 }
291
292 /**
293 * Sets whether the pretty-printer should format *bold*
294 * @deprecated since 1.25
295 * @param bool $help
296 */
297 public function setHelp( $help = true ) {
298 wfDeprecated( __METHOD__, '1.25' );
299 $this->mHelp = $help;
300 }
301
302 /**
303 * Pretty-print various elements in HTML format, such as xml tags and
304 * URLs. This method also escapes characters like <
305 * @deprecated since 1.25
306 * @param string $text
307 * @return string
308 */
309 protected function formatHTML( $text ) {
310 wfDeprecated( __METHOD__, '1.25' );
311
312 // Escape everything first for full coverage
313 $text = htmlspecialchars( $text );
314
315 if ( $this->mFormat === 'XML' || $this->mFormat === 'WDDX' ) {
316 // encode all comments or tags as safe blue strings
317 $text = str_replace( '&lt;', '<span style="color:blue;">&lt;', $text );
318 $text = str_replace( '&gt;', '&gt;</span>', $text );
319 }
320
321 // identify requests to api.php
322 $text = preg_replace( '#^(\s*)(api\.php\?[^ <\n\t]+)$#m', '\1<a href="\2">\2</a>', $text );
323 if ( $this->mHelp ) {
324 // make lines inside * bold
325 $text = preg_replace( '#^(\s*)(\*[^<>\n]+\*)(\s*)$#m', '$1<b>$2</b>$3', $text );
326 }
327
328 // Armor links (bug 61362)
329 $masked = array();
330 $text = preg_replace_callback( '#<a .*?</a>#', function ( $matches ) use ( &$masked ) {
331 $sha = sha1( $matches[0] );
332 $masked[$sha] = $matches[0];
333 return "<$sha>";
334 }, $text );
335
336 // identify URLs
337 $protos = wfUrlProtocolsWithoutProtRel();
338 // This regex hacks around bug 13218 (&quot; included in the URL)
339 $text = preg_replace(
340 "#(((?i)$protos).*?)(&quot;)?([ \\'\"<>\n]|&lt;|&gt;|&quot;)#",
341 '<a href="\\1">\\1</a>\\3\\4',
342 $text
343 );
344
345 // Unarmor links
346 $text = preg_replace_callback( '#<([0-9a-f]{40})>#', function ( $matches ) use ( &$masked ) {
347 $sha = $matches[1];
348 return isset( $masked[$sha] ) ? $masked[$sha] : $matches[0];
349 }, $text );
350
351 /**
352 * Temporary fix for bad links in help messages. As a special case,
353 * XML-escaped metachars are de-escaped one level in the help message
354 * for legibility. Should be removed once we have completed a fully-HTML
355 * version of the help message.
356 */
357 if ( $this->mUnescapeAmps ) {
358 $text = preg_replace( '/&amp;(amp|quot|lt|gt);/', '&\1;', $text );
359 }
360
361 return $text;
362 }
363
364 /**
365 * @see ApiBase::getDescription
366 * @deprecated since 1.25
367 */
368 public function getDescription() {
369 return $this->getIsHtml() ? ' (pretty-print in HTML)' : '';
370 }
371
372 /**
373 * Set the flag to buffer the result instead of printing it.
374 * @deprecated since 1.25, output is always buffered
375 * @param bool $value
376 */
377 public function setBufferResult( $value ) {
378 }
379
380 /**
381 * Formerly indicated whether the formatter needed metadata from ApiResult.
382 *
383 * ApiResult previously (indirectly) used this to decide whether to add
384 * metadata or to ignore calls to metadata-setting methods, which
385 * unfortunately made several methods that should have been static have to
386 * be dynamic instead. Now ApiResult always stores metadata and formatters
387 * are required to ignore it or filter it out.
388 *
389 * @deprecated since 1.25
390 * @return bool
391 */
392 public function getNeedsRawData() {
393 return false;
394 }
395
396 /**@}*/
397 }
398
399 /**
400 * For really cool vim folding this needs to be at the end:
401 * vim: foldmarker=@{,@} foldmethod=marker
402 */