re r66702 Use wfMsgForContent instead of wfMsg
[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 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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;
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 * Initialize the printer function and prepare the output headers, etc.
118 * This method must be the first outputing method during execution.
119 * A help screen's header is printed for the HTML-based output
120 * @param $isError bool Whether an error message is printed
121 */
122 function initPrinter( $isError ) {
123 $isHtml = $this->getIsHtml();
124 $mime = $isHtml ? 'text/html' : $this->getMimeType();
125 $script = wfScript( 'api' );
126
127 // Some printers (ex. Feed) do their own header settings,
128 // in which case $mime will be set to null
129 if ( is_null( $mime ) ) {
130 return; // skip any initialization
131 }
132
133 header( "Content-Type: $mime; charset=utf-8" );
134
135 if ( $isHtml ) {
136 ?>
137 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
138 <html>
139 <head>
140 <?php if ( $this->mUnescapeAmps ) {
141 ?> <title>MediaWiki API</title>
142 <?php } else {
143 ?> <title>MediaWiki API Result</title>
144 <?php } ?>
145 </head>
146 <body>
147 <?php
148
149
150 if ( !$isError ) {
151 ?>
152 <br />
153 <small>
154 You are looking at the HTML representation of the <?php echo( $this->mFormat ); ?> format.<br />
155 HTML is good for debugging, but probably is not suitable for your application.<br />
156 See <a href='http://www.mediawiki.org/wiki/API'>complete documentation</a>, or
157 <a href='<?php echo( $script ); ?>'>API help</a> for more information.
158 </small>
159 <?php
160
161
162 }
163 ?>
164 <pre>
165 <?php
166
167
168 }
169 }
170
171 /**
172 * Finish printing. Closes HTML tags.
173 */
174 public function closePrinter() {
175 if ( $this->getIsHtml() ) {
176 ?>
177
178 </pre>
179 </body>
180 </html>
181 <?php
182
183
184 }
185 }
186
187 /**
188 * The main format printing function. Call it to output the result
189 * string to the user. This function will automatically output HTML
190 * when format name ends in 'fm'.
191 * @param $text string
192 */
193 public function printText( $text ) {
194 if ( $this->mBufferResult ) {
195 $this->mBuffer = $text;
196 } elseif ( $this->getIsHtml() ) {
197 echo $this->formatHTML( $text );
198 } else {
199 // For non-HTML output, clear all errors that might have been
200 // displayed if display_errors=On
201 // Do this only once, of course
202 if ( !$this->mCleared ) {
203 ob_clean();
204 $this->mCleared = true;
205 }
206 echo $text;
207 }
208 }
209
210 /**
211 * Get the contents of the buffer.
212 */
213 public function getBuffer() {
214 return $this->mBuffer;
215 }
216 /**
217 * Set the flag to buffer the result instead of printing it.
218 */
219 public function setBufferResult( $value ) {
220 $this->mBufferResult = $value;
221 }
222
223 /**
224 * Sets whether the pretty-printer should format *bold* and $italics$
225 * @param $help bool
226 */
227 public function setHelp( $help = true ) {
228 $this->mHelp = true;
229 }
230
231 /**
232 * Pretty-print various elements in HTML format, such as xml tags and
233 * URLs. This method also escapes characters like <
234 * @param $text string
235 * @return string
236 */
237 protected function formatHTML( $text ) {
238 global $wgUrlProtocols;
239
240 // Escape everything first for full coverage
241 $text = htmlspecialchars( $text );
242
243 // encode all comments or tags as safe blue strings
244 $text = preg_replace( '/\&lt;(!--.*?--|.*?)\&gt;/', '<span style="color:blue;">&lt;\1&gt;</span>', $text );
245 // identify URLs
246 $protos = implode( "|", $wgUrlProtocols );
247 // This regex hacks around bug 13218 (&quot; included in the URL)
248 $text = preg_replace( "#(($protos).*?)(&quot;)?([ \\'\"<>\n]|&lt;|&gt;|&quot;)#", '<a href="\\1">\\1</a>\\3\\4', $text );
249 // identify requests to api.php
250 $text = preg_replace( "#api\\.php\\?[^ \\()<\n\t]+#", '<a href="\\0">\\0</a>', $text );
251 if ( $this->mHelp ) {
252 // make strings inside * bold
253 $text = preg_replace( "#\\*[^<>\n]+\\*#", '<b>\\0</b>', $text );
254 // make strings inside $ italic
255 $text = preg_replace( "#\\$[^<>\n]+\\$#", '<b><i>\\0</i></b>', $text );
256 }
257
258 /**
259 * Temporary fix for bad links in help messages. As a special case,
260 * XML-escaped metachars are de-escaped one level in the help message
261 * for legibility. Should be removed once we have completed a fully-HTML
262 * version of the help message.
263 */
264 if ( $this->mUnescapeAmps ) {
265 $text = preg_replace( '/&amp;(amp|quot|lt|gt);/', '&\1;', $text );
266 }
267
268 return $text;
269 }
270
271 protected function getExamples() {
272 return 'api.php?action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName();
273 }
274
275 public function getDescription() {
276 return $this->getIsHtml() ? ' (pretty-print in HTML)' : '';
277 }
278
279 public static function getBaseVersion() {
280 return __CLASS__ . ': $Id$';
281 }
282 }
283
284 /**
285 * This printer is used to wrap an instance of the Feed class
286 * @ingroup API
287 */
288 class ApiFormatFeedWrapper extends ApiFormatBase {
289
290 public function __construct( $main ) {
291 parent::__construct( $main, 'feed' );
292 }
293
294 /**
295 * Call this method to initialize output data. See execute()
296 * @param $result ApiResult
297 * @param $feed object an instance of one of the $wgFeedClasses classes
298 * @param $feedItems array of FeedItem objects
299 */
300 public static function setResult( $result, $feed, $feedItems ) {
301 // Store output in the Result data.
302 // This way we can check during execution if any error has occured
303 // Disable size checking for this because we can't continue
304 // cleanly; size checking would cause more problems than it'd
305 // solve
306 $result->disableSizeCheck();
307 $result->addValue( null, '_feed', $feed );
308 $result->addValue( null, '_feeditems', $feedItems );
309 $result->enableSizeCheck();
310 }
311
312 /**
313 * Feed does its own headers
314 */
315 public function getMimeType() {
316 return null;
317 }
318
319 /**
320 * Optimization - no need to sanitize data that will not be needed
321 */
322 public function getNeedsRawData() {
323 return true;
324 }
325
326 /**
327 * This class expects the result data to be in a custom format set by self::setResult()
328 * $result['_feed'] - an instance of one of the $wgFeedClasses classes
329 * $result['_feeditems'] - an array of FeedItem instances
330 */
331 public function execute() {
332 $data = $this->getResultData();
333 if ( isset( $data['_feed'] ) && isset( $data['_feeditems'] ) ) {
334 $feed = $data['_feed'];
335 $items = $data['_feeditems'];
336
337 $feed->outHeader();
338 foreach ( $items as & $item ) {
339 $feed->outItem( $item );
340 }
341 $feed->outFooter();
342 } else {
343 // Error has occured, print something useful
344 ApiBase::dieDebug( __METHOD__, 'Invalid feed class/item' );
345 }
346 }
347
348 public function getVersion() {
349 return __CLASS__ . ': $Id$';
350 }
351 }