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