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