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