4 * Created on Sep 19, 2006
6 * API for MediaWiki 1.8+
8 * Copyright (C) 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 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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;
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'
52 $this->mFormat
= substr($format, 0, -2); // remove ending 'fm'
54 $this->mFormat
= $format;
55 $this->mFormat
= strtoupper($this->mFormat
);
56 $this->mCleared
= false;
60 * Overriding class returns the mime type that should be sent to the client.
61 * This method is not called if getIsHtml() returns true.
64 public abstract function getMimeType();
67 * Whether this formatter needs raw data such as _element tags
70 public function getNeedsRawData() {
75 * Get the internal format name
78 public function getFormat() {
79 return $this->mFormat
;
83 * Specify whether or not sequences like &quot; should be unescaped
84 * to " . This should only be set to true for the help message
85 * when rendered in the default (xmlfm) format. This is a temporary
86 * special-case fix that should be removed once the help has been
87 * reworked to use a fully HTML interface.
89 * @param $b bool Whether or not ampersands should be escaped.
91 public function setUnescapeAmps ( $b ) {
92 $this->mUnescapeAmps
= $b;
96 * Returns true when the HTML pretty-printer should be used.
97 * The default implementation assumes that formats ending with 'fm'
98 * should be formatted in HTML.
101 public function getIsHtml() {
102 return $this->mIsHtml
;
106 * Whether this formatter can format the help message in a nice way.
107 * By default, this returns the same as getIsHtml().
108 * When action=help is set explicitly, the help will always be shown
111 public function getWantsHelp() {
112 return $this->getIsHtml();
116 * Initialize the printer function and prepare the output headers, etc.
117 * This method must be the first outputing method during execution.
118 * A help screen's header is printed for the HTML-based output
119 * @param $isError bool Whether an error message is printed
121 function initPrinter($isError) {
122 $isHtml = $this->getIsHtml();
123 $mime = $isHtml ?
'text/html' : $this->getMimeType();
124 $script = wfScript( 'api' );
126 // Some printers (ex. Feed) do their own header settings,
127 // in which case $mime will be set to null
129 return; // skip any initialization
131 header("Content-Type: $mime; charset=utf-8");
135 <!DOCTYPE HTML
PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
138 <?php
if ($this->mUnescapeAmps
) {
139 ?
> <title
>MediaWiki API
</title
>
141 ?
> <title
>MediaWiki API Result
</title
>
152 You are looking at the HTML representation of the
<?php
echo( $this->mFormat
); ?
> format
.<br
/>
153 HTML is good
for debugging
, but probably is not suitable
for your application
.<br
/>
154 See
<a href
='http://www.mediawiki.org/wiki/API'>complete documentation
</a
>, or
155 <a href
='<?php echo( $script ); ?>'>API help
</a
> for more information
.
170 * Finish printing. Closes HTML tags.
172 public function closePrinter() {
173 if ($this->getIsHtml()) {
186 * The main format printing function. Call it to output the result
187 * string to the user. This function will automatically output HTML
188 * when format name ends in 'fm'.
189 * @param $text string
191 public function printText($text) {
192 if ($this->mBufferResult
) {
193 $this->mBuffer
= $text;
194 } elseif ($this->getIsHtml()) {
195 echo $this->formatHTML($text);
197 // For non-HTML output, clear all errors that might have been
198 // displayed if display_errors=On
199 // Do this only once, of course
203 $this->mCleared
= true;
210 * Get the contents of the buffer.
212 public function getBuffer() {
213 return $this->mBuffer
;
216 * Set the flag to buffer the result instead of printing it.
218 public function setBufferResult( $value ) {
219 $this->mBufferResult
= $value;
223 * Sets whether the pretty-printer should format *bold* and $italics$
226 public function setHelp( $help = true ) {
231 * Prety-print various elements in HTML format, such as xml tags and
232 * URLs. This method also escapes characters like <
233 * @param $text string
236 protected function formatHTML($text) {
237 global $wgUrlProtocols;
239 // Escape everything first for full coverage
240 $text = htmlspecialchars($text);
242 // encode all comments or tags as safe blue strings
243 $text = preg_replace('/\<(!--.*?--|.*?)\>/', '<span style="color:blue;"><\1></span>', $text);
245 $protos = implode("|", $wgUrlProtocols);
246 # This regex hacks around bug 13218 (" included in the URL)
247 $text = preg_replace("#(($protos).*?)(")?([ \\'\"<>\n]|<|>|")#", '<a href="\\1">\\1</a>\\3\\4', $text);
248 // identify requests to api.php
249 $text = preg_replace("#api\\.php\\?[^ \\()<\n\t]+#", '<a href="\\0">\\0</a>', $text);
251 // make strings inside * bold
252 $text = preg_replace("#\\*[^<>\n]+\\*#", '<b>\\0</b>', $text);
253 // make strings inside $ italic
254 $text = preg_replace("#\\$[^<>\n]+\\$#", '<b><i>\\0</i></b>', $text);
257 /* Temporary fix for bad links in help messages. As a special case,
258 * XML-escaped metachars are de-escaped one level in the help message
259 * for legibility. Should be removed once we have completed a fully-html
260 * version of the help message. */
261 if ( $this->mUnescapeAmps
)
262 $text = preg_replace( '/&(amp|quot|lt|gt);/', '&\1;', $text );
267 protected function getExamples() {
268 return 'api.php?action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName();
271 public function getDescription() {
272 return $this->getIsHtml() ?
' (pretty-print in HTML)' : '';
275 public static function getBaseVersion() {
276 return __CLASS__
. ': $Id$';
281 * This printer is used to wrap an instance of the Feed class
284 class ApiFormatFeedWrapper
extends ApiFormatBase
{
286 public function __construct($main) {
287 parent
:: __construct($main, 'feed');
291 * Call this method to initialize output data. See execute()
292 * @param $result ApiResult
293 * @param $feed object an instance of one of the $wgFeedClasses classes
294 * @param $feedItems array of FeedItem objects
296 public static function setResult($result, $feed, $feedItems) {
297 // Store output in the Result data.
298 // This way we can check during execution if any error has occured
299 // Disable size checking for this because we can't continue
300 // cleanly; size checking would cause more problems than it'd
302 $result->disableSizeCheck();
303 $result->addValue(null, '_feed', $feed);
304 $result->addValue(null, '_feeditems', $feedItems);
305 $result->enableSizeCheck();
309 * Feed does its own headers
311 public function getMimeType() {
316 * Optimization - no need to sanitize data that will not be needed
318 public function getNeedsRawData() {
323 * This class expects the result data to be in a custom format set by self::setResult()
324 * $result['_feed'] - an instance of one of the $wgFeedClasses classes
325 * $result['_feeditems'] - an array of FeedItem instances
327 public function execute() {
328 $data = $this->getResultData();
329 if (isset ($data['_feed']) && isset ($data['_feeditems'])) {
330 $feed = $data['_feed'];
331 $items = $data['_feeditems'];
334 foreach ($items as & $item)
335 $feed->outItem($item);
338 // Error has occured, print something useful
339 ApiBase
::dieDebug( __METHOD__
, 'Invalid feed class/item' );
343 public function getVersion() {
344 return __CLASS__
. ': $Id$';