Merge "Made getMaxLag() use caching to reduce connection spam"
[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 * @param bool $b Whether or not ampersands should be escaped.
85 */
86 public function setUnescapeAmps( $b ) {
87 $this->mUnescapeAmps = $b;
88 }
89
90 /**
91 * Returns true when the HTML pretty-printer should be used.
92 * The default implementation assumes that formats ending with 'fm'
93 * should be formatted in HTML.
94 * @return bool
95 */
96 public function getIsHtml() {
97 return $this->mIsHtml;
98 }
99
100 /**
101 * Whether this formatter can format the help message in a nice way.
102 * By default, this returns the same as getIsHtml().
103 * When action=help is set explicitly, the help will always be shown
104 * @return bool
105 */
106 public function getWantsHelp() {
107 return $this->getIsHtml();
108 }
109
110 /**
111 * Disable the formatter completely. This causes calls to initPrinter(),
112 * printText() and closePrinter() to be ignored.
113 */
114 public function disable() {
115 $this->mDisabled = true;
116 }
117
118 public function isDisabled() {
119 return $this->mDisabled;
120 }
121
122 /**
123 * Whether this formatter can handle printing API errors. If this returns
124 * false, then on API errors the default printer will be instantiated.
125 * @since 1.23
126 * @return bool
127 */
128 public function canPrintErrors() {
129 return true;
130 }
131
132 /**
133 * Initialize the printer function and prepare the output headers, etc.
134 * This method must be the first outputting method during execution.
135 * A human-targeted notice about available formats is printed for the HTML-based output,
136 * except for help screens (caused by either an error in the API parameters,
137 * the calling of action=help, or requesting the root script api.php).
138 * @param bool $isHelpScreen Whether a help screen is going to be shown
139 */
140 function initPrinter( $isHelpScreen ) {
141 if ( $this->mDisabled ) {
142 return;
143 }
144 $isHtml = $this->getIsHtml();
145 $mime = $isHtml ? 'text/html' : $this->getMimeType();
146 $script = wfScript( 'api' );
147
148 // Some printers (ex. Feed) do their own header settings,
149 // in which case $mime will be set to null
150 if ( is_null( $mime ) ) {
151 return; // skip any initialization
152 }
153
154 $this->getMain()->getRequest()->response()->header( "Content-Type: $mime; charset=utf-8" );
155
156 //Set X-Frame-Options API results (bug 39180)
157 $apiFrameOptions = $this->getConfig()->get( 'ApiFrameOptions' );
158 if ( $apiFrameOptions ) {
159 $this->getMain()->getRequest()->response()->header( "X-Frame-Options: $apiFrameOptions" );
160 }
161
162 if ( $isHtml ) {
163 ?>
164 <!DOCTYPE HTML>
165 <html>
166 <head>
167 <?php
168 if ( $this->mUnescapeAmps ) {
169 ?> <title>MediaWiki API</title>
170 <?php
171 } else {
172 ?> <title>MediaWiki API Result</title>
173 <?php
174 }
175 ?>
176 </head>
177 <body>
178 <?php
179 if ( !$isHelpScreen ) {
180 // @codingStandardsIgnoreStart Exclude long line from CodeSniffer checks
181 ?>
182 <br />
183 <small>
184 You are looking at the HTML representation of the <?php echo $this->mFormat; ?> format.<br />
185 HTML is good for debugging, but is unsuitable for application use.<br />
186 Specify the format parameter to change the output format.<br />
187 To see the non HTML representation of the <?php echo $this->mFormat; ?> format, set format=<?php echo strtolower( $this->mFormat ); ?>.<br />
188 See the <a href='https://www.mediawiki.org/wiki/API'>complete documentation</a>, or
189 <a href='<?php echo $script; ?>'>API help</a> for more information.
190 </small>
191 <pre style='white-space: pre-wrap;'>
192 <?php
193 // @codingStandardsIgnoreEnd
194 // don't wrap the contents of the <pre> for help screens
195 // because these are actually formatted to rely on
196 // the monospaced font for layout purposes
197 } else {
198 ?>
199 <pre>
200 <?php
201 }
202 }
203 }
204
205 /**
206 * Finish printing. Closes HTML tags.
207 */
208 public function closePrinter() {
209 if ( $this->mDisabled ) {
210 return;
211 }
212 if ( $this->getIsHtml() ) {
213 ?>
214
215 </pre>
216 </body>
217 </html>
218 <?php
219 }
220 }
221
222 /**
223 * The main format printing function. Call it to output the result
224 * string to the user. This function will automatically output HTML
225 * when format name ends in 'fm'.
226 * @param string $text
227 */
228 public function printText( $text ) {
229 if ( $this->mDisabled ) {
230 return;
231 }
232 if ( $this->mBufferResult ) {
233 $this->mBuffer = $text;
234 } elseif ( $this->getIsHtml() ) {
235 echo $this->formatHTML( $text );
236 } else {
237 // For non-HTML output, clear all errors that might have been
238 // displayed if display_errors=On
239 // Do this only once, of course
240 if ( !$this->mCleared ) {
241 ob_clean();
242 $this->mCleared = true;
243 }
244 echo $text;
245 }
246 }
247
248 /**
249 * Get the contents of the buffer.
250 */
251 public function getBuffer() {
252 return $this->mBuffer;
253 }
254
255 /**
256 * Set the flag to buffer the result instead of printing it.
257 * @param bool $value
258 */
259 public function setBufferResult( $value ) {
260 $this->mBufferResult = $value;
261 }
262
263 /**
264 * Sets whether the pretty-printer should format *bold*
265 * @param bool $help
266 */
267 public function setHelp( $help = true ) {
268 $this->mHelp = $help;
269 }
270
271 /**
272 * Pretty-print various elements in HTML format, such as xml tags and
273 * URLs. This method also escapes characters like <
274 * @param string $text
275 * @return string
276 */
277 protected function formatHTML( $text ) {
278 // Escape everything first for full coverage
279 $text = htmlspecialchars( $text );
280 // encode all comments or tags as safe blue strings
281 $text = str_replace( '&lt;', '<span style="color:blue;">&lt;', $text );
282 $text = str_replace( '&gt;', '&gt;</span>', $text );
283
284 // identify requests to api.php
285 $text = preg_replace( '#^(\s*)(api\.php\?[^ <\n\t]+)$#m', '\1<a href="\2">\2</a>', $text );
286 if ( $this->mHelp ) {
287 // make lines inside * bold
288 $text = preg_replace( '#^(\s*)(\*[^<>\n]+\*)(\s*)$#m', '$1<b>$2</b>$3', $text );
289 }
290
291 // Armor links (bug 61362)
292 $masked = array();
293 $text = preg_replace_callback( '#<a .*?</a>#', function ( $matches ) use ( &$masked ) {
294 $sha = sha1( $matches[0] );
295 $masked[$sha] = $matches[0];
296 return "<$sha>";
297 }, $text );
298
299 // identify URLs
300 $protos = wfUrlProtocolsWithoutProtRel();
301 // This regex hacks around bug 13218 (&quot; included in the URL)
302 $text = preg_replace(
303 "#(((?i)$protos).*?)(&quot;)?([ \\'\"<>\n]|&lt;|&gt;|&quot;)#",
304 '<a href="\\1">\\1</a>\\3\\4',
305 $text
306 );
307
308 // Unarmor links
309 $text = preg_replace_callback( '#<([0-9a-f]{40})>#', function ( $matches ) use ( &$masked ) {
310 $sha = $matches[1];
311 return isset( $masked[$sha] ) ? $masked[$sha] : $matches[0];
312 }, $text );
313
314 /**
315 * Temporary fix for bad links in help messages. As a special case,
316 * XML-escaped metachars are de-escaped one level in the help message
317 * for legibility. Should be removed once we have completed a fully-HTML
318 * version of the help message.
319 */
320 if ( $this->mUnescapeAmps ) {
321 $text = preg_replace( '/&amp;(amp|quot|lt|gt);/', '&\1;', $text );
322 }
323
324 return $text;
325 }
326
327 public function getExamples() {
328 return array(
329 'api.php?action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName()
330 => "Format the query result in the {$this->getModuleName()} format",
331 );
332 }
333
334 public function getHelpUrls() {
335 return 'https://www.mediawiki.org/wiki/API:Data_formats';
336 }
337
338 public function getDescription() {
339 return $this->getIsHtml() ? ' (pretty-print in HTML)' : '';
340 }
341 }
342
343 /**
344 * This printer is used to wrap an instance of the Feed class
345 * @ingroup API
346 */
347 class ApiFormatFeedWrapper extends ApiFormatBase {
348
349 public function __construct( ApiMain $main ) {
350 parent::__construct( $main, 'feed' );
351 }
352
353 /**
354 * Call this method to initialize output data. See execute()
355 * @param ApiResult $result
356 * @param object $feed An instance of one of the $wgFeedClasses classes
357 * @param array $feedItems of FeedItem objects
358 */
359 public static function setResult( $result, $feed, $feedItems ) {
360 // Store output in the Result data.
361 // This way we can check during execution if any error has occurred
362 // Disable size checking for this because we can't continue
363 // cleanly; size checking would cause more problems than it'd
364 // solve
365 $result->disableSizeCheck();
366 $result->addValue( null, '_feed', $feed );
367 $result->addValue( null, '_feeditems', $feedItems );
368 $result->enableSizeCheck();
369 }
370
371 /**
372 * Feed does its own headers
373 *
374 * @return null
375 */
376 public function getMimeType() {
377 return null;
378 }
379
380 /**
381 * Optimization - no need to sanitize data that will not be needed
382 *
383 * @return bool
384 */
385 public function getNeedsRawData() {
386 return true;
387 }
388
389 /**
390 * ChannelFeed doesn't give us a method to print errors in a friendly
391 * manner, so just punt errors to the default printer.
392 * @return bool
393 */
394 public function canPrintErrors() {
395 return false;
396 }
397
398 /**
399 * This class expects the result data to be in a custom format set by self::setResult()
400 * $result['_feed'] - an instance of one of the $wgFeedClasses classes
401 * $result['_feeditems'] - an array of FeedItem instances
402 */
403 public function execute() {
404 $data = $this->getResultData();
405 if ( isset( $data['_feed'] ) && isset( $data['_feeditems'] ) ) {
406 $feed = $data['_feed'];
407 $items = $data['_feeditems'];
408
409 $feed->outHeader();
410 foreach ( $items as & $item ) {
411 $feed->outItem( $item );
412 }
413 $feed->outFooter();
414 } else {
415 // Error has occurred, print something useful
416 ApiBase::dieDebug( __METHOD__, 'Invalid feed class/item' );
417 }
418 }
419 }