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;
41 * Create a new instance of the formatter.
42 * If the format name ends with 'fm', wrap its output in the proper HTML.
44 public function __construct($main, $format) {
45 parent
:: __construct($main, $format);
47 $this->mIsHtml
= (substr($format, -2, 2) === 'fm'); // ends with 'fm'
49 $this->mFormat
= substr($format, 0, -2); // remove ending 'fm'
51 $this->mFormat
= $format;
52 $this->mFormat
= strtoupper($this->mFormat
);
56 * Overriding class returns the mime type that should be sent to the client.
57 * This method is not called if getIsHtml() returns true.
60 public abstract function getMimeType();
63 * If formatter outputs data results as is, the results must first be sanitized.
64 * An XML formatter on the other hand uses special tags, such as "_element" for special handling,
65 * and thus needs to override this function to return true.
67 public function getNeedsRawData() {
72 * Specify whether or not ampersands should be escaped to '&' when rendering. This
73 * should only be set to true for the help message when rendered in the default (xmlfm)
74 * format. This is a temporary special-case fix that should be removed once the help
75 * has been reworked to use a fully html interface.
77 * @param boolean Whether or not ampersands should be escaped.
79 public function setUnescapeAmps ( $b ) {
80 $this->mUnescapeAmps
= $b;
84 * Returns true when an HTML filtering printer should be used.
85 * The default implementation assumes that formats ending with 'fm'
86 * should be formatted in HTML.
88 public function getIsHtml() {
89 return $this->mIsHtml
;
93 * Initialize the printer function and prepares the output headers, etc.
94 * This method must be the first outputing method during execution.
95 * A help screen's header is printed for the HTML-based output
97 function initPrinter($isError) {
98 $isHtml = $this->getIsHtml();
99 $mime = $isHtml ?
'text/html' : $this->getMimeType();
100 $script = wfScript( 'api' );
102 // Some printers (ex. Feed) do their own header settings,
103 // in which case $mime will be set to null
105 return; // skip any initialization
107 header("Content-Type: $mime; charset=utf-8");
111 <!DOCTYPE HTML
PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
114 <?php
if ($this->mUnescapeAmps
) {
115 ?
> <title
>MediaWiki API
</title
>
117 ?
> <title
>MediaWiki API Result
</title
>
128 You are looking at the HTML representation of the
<?php
echo( $this->mFormat
); ?
> format
.<br
/>
129 HTML is good
for debugging
, but probably is not suitable
for your application
.<br
/>
130 See
<a href
='http://www.mediawiki.org/wiki/API'>complete documentation
</a
>, or
131 <a href
='<?php echo( $script ); ?>'>API help
</a
> for more information
.
146 * Finish printing. Closes HTML tags.
148 public function closePrinter() {
149 if ($this->getIsHtml()) {
162 * The main format printing function. Call it to output the result string to the user.
163 * This function will automatically output HTML when format name ends in 'fm'.
165 public function printText($text) {
166 if ($this->getIsHtml())
167 echo $this->formatHTML($text);
173 * Prety-print various elements in HTML format, such as xml tags and URLs.
174 * This method also replaces any '<' with <
176 protected function formatHTML($text) {
177 // Escape everything first for full coverage
178 $text = htmlspecialchars($text);
180 // encode all comments or tags as safe blue strings
181 $text = preg_replace('/\<(!--.*?--|.*?)\>/', '<span style="color:blue;"><\1></span>', $text);
183 $protos = "http|https|ftp|gopher";
184 $text = ereg_replace("($protos)://[^ \\'\"()<\n]+", '<a href="\\0">\\0</a>', $text);
185 // identify requests to api.php
186 $text = ereg_replace("api\\.php\\?[^ \\()<\n\t]+", '<a href="\\0">\\0</a>', $text);
187 // make strings inside * bold
188 $text = ereg_replace("\\*[^<>\n]+\\*", '<b>\\0</b>', $text);
189 // make strings inside $ italic
190 $text = ereg_replace("\\$[^<>\n]+\\$", '<b><i>\\0</i></b>', $text);
192 /* Temporary fix for bad links in help messages. As a special case,
193 * XML-escaped metachars are de-escaped one level in the help message
194 * for legibility. Should be removed once we have completed a fully-html
195 * version of the help message. */
196 if ( $this->mUnescapeAmps
)
197 $text = preg_replace( '/&(amp|quot|lt|gt);/', '&\1;', $text );
203 * Returns usage examples for this format.
205 protected function getExamples() {
206 return 'api.php?action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName();
209 protected function getDescription() {
210 return $this->getIsHtml() ?
' (pretty-print in HTML)' : '';
213 public static function getBaseVersion() {
214 return __CLASS__
. ': $Id$';
219 * This printer is used to wrap an instance of the Feed class
222 class ApiFormatFeedWrapper
extends ApiFormatBase
{
224 public function __construct($main) {
225 parent
:: __construct($main, 'feed');
229 * Call this method to initialize output data. See self::execute()
231 public static function setResult($result, $feed, $feedItems) {
232 // Store output in the Result data.
233 // This way we can check during execution if any error has occured
234 $data = & $result->getData();
235 $data['_feed'] = $feed;
236 $data['_feeditems'] = $feedItems;
240 * Feed does its own headers
242 public function getMimeType() {
247 * Optimization - no need to sanitize data that will not be needed
249 public function getNeedsRawData() {
254 * This class expects the result data to be in a custom format set by self::setResult()
255 * $result['_feed'] - an instance of one of the $wgFeedClasses classes
256 * $result['_feeditems'] - an array of FeedItem instances
258 public function execute() {
259 $data = $this->getResultData();
260 if (isset ($data['_feed']) && isset ($data['_feeditems'])) {
261 $feed = $data['_feed'];
262 $items = $data['_feeditems'];
265 foreach ($items as & $item)
266 $feed->outItem($item);
269 // Error has occured, print something usefull
270 // TODO: make this error more informative using ApiBase :: dieDebug() or similar
271 wfHttpError(500, 'Internal Server Error', '');
275 public function getVersion() {
276 return __CLASS__
. ': $Id$';
281 * This printer is used to wrap raw printer
284 class ApiFormatRaw
extends ApiFormatBase
{
286 public function __construct($main, $format) {
287 parent
:: __construct($main, $format);
290 public static function setRawData( $result, $raw_data, $raw_type = 'text/plain' ) {
291 $data = & $result->getData();
292 $data['_raw'] = $raw_data;
293 $data['_raw_mimetype'] = $raw_type;
296 public function getMimeType() {
297 $data = $this->getResultData();
298 if( !isset( $data['_raw_mimetype'] ) && !isset( $data['error'] ) ) {
299 ApiBase
:: dieDebug( 'ApiFormatRaw', 'No raw data is set for this module' );
302 elseif( isset( $data['error'] ) ) {
303 $this->executeError( $data );
306 return $data['_raw_mimetype'];
309 public function execute() {
310 $data = $this->getResultData();
311 if( !isset( $data['_raw'] ) && !isset( $data['error'] ) ) {
312 ApiBase
:: dieDebug( 'ApiFormatRaw', 'No raw data is set for this module' );
315 elseif( isset( $data['error'] ) ) {
316 $this->executeError( $data );
319 $this->printText( $data['_raw'] );
322 private function executeError( $data ) {
323 wfHttpError(500, 'Internal Server Error', '');
324 echo "{$data['error']['code']}\n";
325 echo "{$data['error']['info']}\n";
328 public function getNeedsRawData() {
332 protected function getDescription() {
333 return 'Output data in raw format. NOTE: not all actions support it' . parent
:: getDescription();
336 public function getVersion() {
337 return __CLASS__
. ': $Id$';