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