493e866d8d9e44fb2f9c0f69819806d24a656527
[lhc/web/wiklou.git] / includes / api / ApiFormatBase.php
1 <?php
2
3 /**
4 * Created on Sep 19, 2006
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright © 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 */
25
26 if ( !defined( 'MEDIAWIKI' ) ) {
27 // Eclipse helper - will be ignored in production
28 require_once( 'ApiBase.php' );
29 }
30
31 /**
32 * This is the abstract base class for API formatters.
33 *
34 * @ingroup API
35 */
36 abstract class ApiFormatBase extends ApiBase {
37
38 private $mIsHtml, $mFormat, $mUnescapeAmps, $mHelp, $mCleared;
39 private $mBufferResult = false, $mBuffer, $mDisabled = false;
40
41 /**
42 * Constructor
43 * If $format ends with 'fm', pretty-print the output in HTML.
44 * @param $main ApiMain
45 * @param $format string Format name
46 */
47 public function __construct( $main, $format ) {
48 parent::__construct( $main, $format );
49
50 $this->mIsHtml = ( substr( $format, - 2, 2 ) === 'fm' ); // ends with 'fm'
51 if ( $this->mIsHtml ) {
52 $this->mFormat = substr( $format, 0, - 2 ); // remove ending 'fm'
53 } else {
54 $this->mFormat = $format;
55 }
56 $this->mFormat = strtoupper( $this->mFormat );
57 $this->mCleared = false;
58 }
59
60 /**
61 * Overriding class returns the mime type that should be sent to the client.
62 * This method is not called if getIsHtml() returns true.
63 * @return string
64 */
65 public abstract function getMimeType();
66
67 /**
68 * Whether this formatter needs raw data such as _element tags
69 * @return bool
70 */
71 public function getNeedsRawData() {
72 return false;
73 }
74
75 /**
76 * Get the internal format name
77 * @return string
78 */
79 public function getFormat() {
80 return $this->mFormat;
81 }
82
83 /**
84 * Specify whether or not sequences like &amp;quot; should be unescaped
85 * to &quot; . This should only be set to true for the help message
86 * when rendered in the default (xmlfm) format. This is a temporary
87 * special-case fix that should be removed once the help has been
88 * reworked to use a fully HTML interface.
89 *
90 * @param $b bool Whether or not ampersands should be escaped.
91 */
92 public function setUnescapeAmps ( $b ) {
93 $this->mUnescapeAmps = $b;
94 }
95
96 /**
97 * Returns true when the HTML pretty-printer should be used.
98 * The default implementation assumes that formats ending with 'fm'
99 * should be formatted in HTML.
100 * @return bool
101 */
102 public function getIsHtml() {
103 return $this->mIsHtml;
104 }
105
106 /**
107 * Whether this formatter can format the help message in a nice way.
108 * By default, this returns the same as getIsHtml().
109 * When action=help is set explicitly, the help will always be shown
110 * @return bool
111 */
112 public function getWantsHelp() {
113 return $this->getIsHtml();
114 }
115
116 /**
117 * Disable the formatter completely. This causes calls to initPrinter(),
118 * printText() and closePrinter() to be ignored.
119 */
120 public function disable() {
121 $this->mDisabled = true;
122 }
123
124 public function isDisabled() {
125 return $this->mDisabled;
126 }
127
128 /**
129 * Initialize the printer function and prepare the output headers, etc.
130 * This method must be the first outputing method during execution.
131 * A help screen's header is printed for the HTML-based output
132 * @param $isError bool Whether an error message is printed
133 */
134 function initPrinter( $isError ) {
135 if ( $this->mDisabled ) {
136 return;
137 }
138 $isHtml = $this->getIsHtml();
139 $mime = $isHtml ? 'text/html' : $this->getMimeType();
140 $script = wfScript( 'api' );
141
142 // Some printers (ex. Feed) do their own header settings,
143 // in which case $mime will be set to null
144 if ( is_null( $mime ) ) {
145 return; // skip any initialization
146 }
147
148 header( "Content-Type: $mime; charset=utf-8" );
149
150 if ( $isHtml ) {
151 ?>
152 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
153 <html>
154 <head>
155 <?php if ( $this->mUnescapeAmps ) {
156 ?> <title>MediaWiki API</title>
157 <?php } else {
158 ?> <title>MediaWiki API Result</title>
159 <?php } ?>
160 </head>
161 <body>
162 <?php
163
164
165 if ( !$isError ) {
166 ?>
167 <br />
168 <small>
169 You are looking at the HTML representation of the <?php echo( $this->mFormat ); ?> format.<br />
170 HTML is good for debugging, but probably is not suitable for your application.<br />
171 See <a href='http://www.mediawiki.org/wiki/API'>complete documentation</a>, or
172 <a href='<?php echo( $script ); ?>'>API help</a> for more information.
173 </small>
174 <?php
175
176
177 }
178 ?>
179 <pre>
180 <?php
181
182
183 }
184 }
185
186 /**
187 * Finish printing. Closes HTML tags.
188 */
189 public function closePrinter() {
190 if ( $this->mDisabled ) {
191 return;
192 }
193 if ( $this->getIsHtml() ) {
194 ?>
195
196 </pre>
197 </body>
198 </html>
199 <?php
200
201
202 }
203 }
204
205 /**
206 * The main format printing function. Call it to output the result
207 * string to the user. This function will automatically output HTML
208 * when format name ends in 'fm'.
209 * @param $text string
210 */
211 public function printText( $text ) {
212 if ( $this->mDisabled ) {
213 return;
214 }
215 if ( $this->mBufferResult ) {
216 $this->mBuffer = $text;
217 } elseif ( $this->getIsHtml() ) {
218 echo $this->formatHTML( $text );
219 } else {
220 // For non-HTML output, clear all errors that might have been
221 // displayed if display_errors=On
222 // Do this only once, of course
223 if ( !$this->mCleared ) {
224 ob_clean();
225 $this->mCleared = true;
226 }
227 echo $text;
228 }
229 }
230
231 /**
232 * Get the contents of the buffer.
233 */
234 public function getBuffer() {
235 return $this->mBuffer;
236 }
237 /**
238 * Set the flag to buffer the result instead of printing it.
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 = true;
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 global $wgUrlProtocols;
260
261 // Escape everything first for full coverage
262 $text = htmlspecialchars( $text );
263
264 // encode all comments or tags as safe blue strings
265 $text = preg_replace( '/\&lt;(!--.*?--|.*?)\&gt;/', '<span style="color:blue;">&lt;\1&gt;</span>', $text );
266 // identify URLs
267 $protos = implode( "|", $wgUrlProtocols );
268 // This regex hacks around bug 13218 (&quot; included in the URL)
269 $text = preg_replace( "#(($protos).*?)(&quot;)?([ \\'\"<>\n]|&lt;|&gt;|&quot;)#", '<a href="\\1">\\1</a>\\3\\4', $text );
270 // identify requests to api.php
271 $text = preg_replace( "#api\\.php\\?[^ \\()<\n\t]+#", '<a href="\\0">\\0</a>', $text );
272 if ( $this->mHelp ) {
273 // make strings inside * bold
274 $text = preg_replace( "#\\*[^<>\n]+\\*#", '<b>\\0</b>', $text );
275 // make strings inside $ italic
276 $text = preg_replace( "#\\$[^<>\n]+\\$#", '<b><i>\\0</i></b>', $text );
277 }
278
279 /**
280 * Temporary fix for bad links in help messages. As a special case,
281 * XML-escaped metachars are de-escaped one level in the help message
282 * for legibility. Should be removed once we have completed a fully-HTML
283 * version of the help message.
284 */
285 if ( $this->mUnescapeAmps ) {
286 $text = preg_replace( '/&amp;(amp|quot|lt|gt);/', '&\1;', $text );
287 }
288
289 return $text;
290 }
291
292 protected function getExamples() {
293 return 'api.php?action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName();
294 }
295
296 public function getDescription() {
297 return $this->getIsHtml() ? ' (pretty-print in HTML)' : '';
298 }
299
300 public static function getBaseVersion() {
301 return __CLASS__ . ': $Id$';
302 }
303 }
304
305 /**
306 * This printer is used to wrap an instance of the Feed class
307 * @ingroup API
308 */
309 class ApiFormatFeedWrapper extends ApiFormatBase {
310
311 public function __construct( $main ) {
312 parent::__construct( $main, 'feed' );
313 }
314
315 /**
316 * Call this method to initialize output data. See execute()
317 * @param $result ApiResult
318 * @param $feed object an instance of one of the $wgFeedClasses classes
319 * @param $feedItems array of FeedItem objects
320 */
321 public static function setResult( $result, $feed, $feedItems ) {
322 // Store output in the Result data.
323 // This way we can check during execution if any error has occured
324 // Disable size checking for this because we can't continue
325 // cleanly; size checking would cause more problems than it'd
326 // solve
327 $result->disableSizeCheck();
328 $result->addValue( null, '_feed', $feed );
329 $result->addValue( null, '_feeditems', $feedItems );
330 $result->enableSizeCheck();
331 }
332
333 /**
334 * Feed does its own headers
335 */
336 public function getMimeType() {
337 return null;
338 }
339
340 /**
341 * Optimization - no need to sanitize data that will not be needed
342 */
343 public function getNeedsRawData() {
344 return true;
345 }
346
347 /**
348 * This class expects the result data to be in a custom format set by self::setResult()
349 * $result['_feed'] - an instance of one of the $wgFeedClasses classes
350 * $result['_feeditems'] - an array of FeedItem instances
351 */
352 public function execute() {
353 $data = $this->getResultData();
354 if ( isset( $data['_feed'] ) && isset( $data['_feeditems'] ) ) {
355 $feed = $data['_feed'];
356 $items = $data['_feeditems'];
357
358 $feed->outHeader();
359 foreach ( $items as & $item ) {
360 $feed->outItem( $item );
361 }
362 $feed->outFooter();
363 } else {
364 // Error has occured, print something useful
365 ApiBase::dieDebug( __METHOD__, 'Invalid feed class/item' );
366 }
367 }
368
369 public function getVersion() {
370 return __CLASS__ . ': $Id$';
371 }
372 }