4 * Created on Sep 19, 2006
6 * API for MediaWiki 1.8+
8 * Copyright © 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
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.
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.
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
26 if ( !defined( 'MEDIAWIKI' ) ) {
27 // Eclipse helper - will be ignored in production
28 require_once( 'ApiBase.php' );
32 * This is the abstract base class for API formatters.
36 abstract class ApiFormatBase
extends ApiBase
{
38 private $mIsHtml, $mFormat, $mUnescapeAmps, $mHelp, $mCleared;
39 private $mBufferResult = false, $mBuffer, $mDisabled = false;
43 * If $format ends with 'fm', pretty-print the output in HTML.
44 * @param $main ApiMain
45 * @param $format string Format name
47 public function __construct( $main, $format ) {
48 parent
::__construct( $main, $format );
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'
54 $this->mFormat
= $format;
56 $this->mFormat
= strtoupper( $this->mFormat
);
57 $this->mCleared
= false;
61 * Overriding class returns the mime type that should be sent to the client.
62 * This method is not called if getIsHtml() returns true.
65 public abstract function getMimeType();
68 * Whether this formatter needs raw data such as _element tags
71 public function getNeedsRawData() {
76 * Get the internal format name
79 public function getFormat() {
80 return $this->mFormat
;
84 * Specify whether or not sequences like &quot; should be unescaped
85 * to " . 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.
90 * @param $b bool Whether or not ampersands should be escaped.
92 public function setUnescapeAmps ( $b ) {
93 $this->mUnescapeAmps
= $b;
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.
102 public function getIsHtml() {
103 return $this->mIsHtml
;
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
112 public function getWantsHelp() {
113 return $this->getIsHtml();
117 * Disable the formatter completely. This causes calls to initPrinter(),
118 * printText() and closePrinter() to be ignored.
120 public function disable() {
121 $this->mDisabled
= true;
124 public function isDisabled() {
125 return $this->mDisabled
;
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
134 function initPrinter( $isError ) {
135 if ( $this->mDisabled
) {
138 $isHtml = $this->getIsHtml();
139 $mime = $isHtml ?
'text/html' : $this->getMimeType();
140 $script = wfScript( 'api' );
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
148 header( "Content-Type: $mime; charset=utf-8" );
152 <!DOCTYPE HTML
PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
155 <?php
if ( $this->mUnescapeAmps
) {
156 ?
> <title
>MediaWiki API
</title
>
158 ?
> <title
>MediaWiki API Result
</title
>
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
.
187 * Finish printing. Closes HTML tags.
189 public function closePrinter() {
190 if ( $this->mDisabled
) {
193 if ( $this->getIsHtml() ) {
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
211 public function printText( $text ) {
212 if ( $this->mDisabled
) {
215 if ( $this->mBufferResult
) {
216 $this->mBuffer
= $text;
217 } elseif ( $this->getIsHtml() ) {
218 echo $this->formatHTML( $text );
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
) {
225 $this->mCleared
= true;
232 * Get the contents of the buffer.
234 public function getBuffer() {
235 return $this->mBuffer
;
238 * Set the flag to buffer the result instead of printing it.
240 public function setBufferResult( $value ) {
241 $this->mBufferResult
= $value;
245 * Sets whether the pretty-printer should format *bold* and $italics$
248 public function setHelp( $help = true ) {
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
258 protected function formatHTML( $text ) {
259 global $wgUrlProtocols;
261 // Escape everything first for full coverage
262 $text = htmlspecialchars( $text );
264 // encode all comments or tags as safe blue strings
265 $text = preg_replace( '/\<(!--.*?--|.*?)\>/', '<span style="color:blue;"><\1></span>', $text );
267 $protos = implode( "|", $wgUrlProtocols );
268 // This regex hacks around bug 13218 (" included in the URL)
269 $text = preg_replace( "#(($protos).*?)(")?([ \\'\"<>\n]|<|>|")#", '<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 );
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.
285 if ( $this->mUnescapeAmps
) {
286 $text = preg_replace( '/&(amp|quot|lt|gt);/', '&\1;', $text );
292 protected function getExamples() {
293 return 'api.php?action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName();
296 public function getDescription() {
297 return $this->getIsHtml() ?
' (pretty-print in HTML)' : '';
300 public static function getBaseVersion() {
301 return __CLASS__
. ': $Id$';
306 * This printer is used to wrap an instance of the Feed class
309 class ApiFormatFeedWrapper
extends ApiFormatBase
{
311 public function __construct( $main ) {
312 parent
::__construct( $main, 'feed' );
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
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
327 $result->disableSizeCheck();
328 $result->addValue( null, '_feed', $feed );
329 $result->addValue( null, '_feeditems', $feedItems );
330 $result->enableSizeCheck();
334 * Feed does its own headers
336 public function getMimeType() {
341 * Optimization - no need to sanitize data that will not be needed
343 public function getNeedsRawData() {
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
352 public function execute() {
353 $data = $this->getResultData();
354 if ( isset( $data['_feed'] ) && isset( $data['_feeditems'] ) ) {
355 $feed = $data['_feed'];
356 $items = $data['_feeditems'];
359 foreach ( $items as & $item ) {
360 $feed->outItem( $item );
364 // Error has occured, print something useful
365 ApiBase
::dieDebug( __METHOD__
, 'Invalid feed class/item' );
369 public function getVersion() {
370 return __CLASS__
. ': $Id$';