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