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