Like the comment says... dieDebug() instead of wfHttpError
[mediawiki.git] / includes / api / ApiFormatBase.php
blobbe131b379ce93e0872ad5f695dcaab0a2f292419
1 <?php
3 /*
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');
31 /**
32 * This is the abstract base class for API formatters.
34 * @ingroup API
36 abstract class ApiFormatBase extends ApiBase {
38 private $mIsHtml, $mFormat, $mUnescapeAmps, $mHelp, $mCleared;
40 /**
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'
48 if ($this->mIsHtml)
49 $this->mFormat = substr($format, 0, -2); // remove ending 'fm'
50 else
51 $this->mFormat = $format;
52 $this->mFormat = strtoupper($this->mFormat);
53 $this->mCleared = false;
56 /**
57 * Overriding class returns the mime type that should be sent to the client.
58 * This method is not called if getIsHtml() returns true.
59 * @return string
61 public abstract function getMimeType();
63 /**
64 * If formatter outputs data results as is, the results must first be sanitized.
65 * An XML formatter on the other hand uses special tags, such as "_element" for special handling,
66 * and thus needs to override this function to return true.
68 public function getNeedsRawData() {
69 return false;
72 /**
73 * Specify whether or not ampersands should be escaped to '&amp;' when rendering. This
74 * should only be set to true for the help message when rendered in the default (xmlfm)
75 * format. This is a temporary special-case fix that should be removed once the help
76 * has been reworked to use a fully html interface.
78 * @param boolean Whether or not ampersands should be escaped.
80 public function setUnescapeAmps ( $b ) {
81 $this->mUnescapeAmps = $b;
84 /**
85 * Returns true when an HTML filtering printer should be used.
86 * The default implementation assumes that formats ending with 'fm'
87 * should be formatted in HTML.
89 public function getIsHtml() {
90 return $this->mIsHtml;
93 /**
94 * Initialize the printer function and prepares the output headers, etc.
95 * This method must be the first outputing method during execution.
96 * A help screen's header is printed for the HTML-based output
98 function initPrinter($isError) {
99 $isHtml = $this->getIsHtml();
100 $mime = $isHtml ? 'text/html' : $this->getMimeType();
101 $script = wfScript( 'api' );
103 // Some printers (ex. Feed) do their own header settings,
104 // in which case $mime will be set to null
105 if (is_null($mime))
106 return; // skip any initialization
108 header("Content-Type: $mime; charset=utf-8");
110 if ($isHtml) {
112 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
113 <html>
114 <head>
115 <?php if ($this->mUnescapeAmps) {
116 ?> <title>MediaWiki API</title>
117 <?php } else {
118 ?> <title>MediaWiki API Result</title>
119 <?php } ?>
120 </head>
121 <body>
122 <?php
125 if( !$isError ) {
127 <br/>
128 <small>
129 You are looking at the HTML representation of the <?php echo( $this->mFormat ); ?> format.<br/>
130 HTML is good for debugging, but probably is not suitable for your application.<br/>
131 See <a href='http://www.mediawiki.org/wiki/API'>complete documentation</a>, or
132 <a href='<?php echo( $script ); ?>'>API help</a> for more information.
133 </small>
134 <?php
139 <pre>
140 <?php
147 * Finish printing. Closes HTML tags.
149 public function closePrinter() {
150 if ($this->getIsHtml()) {
153 </pre>
154 </body>
155 </html>
156 <?php
163 * The main format printing function. Call it to output the result string to the user.
164 * This function will automatically output HTML when format name ends in 'fm'.
166 public function printText($text) {
167 if ($this->getIsHtml())
168 echo $this->formatHTML($text);
169 else
171 // For non-HTML output, clear all errors that might have been
172 // displayed if display_errors=On
173 // Do this only once, of course
174 if(!$this->mCleared)
176 ob_clean();
177 $this->mCleared = true;
179 echo $text;
184 * Says pretty-printer that it should use *bold* and $italics$ formatting
186 public function setHelp( $help = true ) {
187 $this->mHelp = true;
191 * Prety-print various elements in HTML format, such as xml tags and URLs.
192 * This method also replaces any '<' with &lt;
194 protected function formatHTML($text) {
195 // Escape everything first for full coverage
196 $text = htmlspecialchars($text);
198 // encode all comments or tags as safe blue strings
199 $text = preg_replace('/\&lt;(!--.*?--|.*?)\&gt;/', '<span style="color:blue;">&lt;\1&gt;</span>', $text);
200 // identify URLs
201 $protos = "http|https|ftp|gopher";
202 # This regex hacks around bug 13218 (&quot; included in the URL)
203 $text = preg_replace("#(($protos)://.*?)(&quot;)?([ \\'\"()<\n])#", '<a href="\\1">\\1</a>\\3\\4', $text);
204 // identify requests to api.php
205 $text = preg_replace("#api\\.php\\?[^ \\()<\n\t]+#", '<a href="\\0">\\0</a>', $text);
206 if( $this->mHelp ) {
207 // make strings inside * bold
208 $text = ereg_replace("\\*[^<>\n]+\\*", '<b>\\0</b>', $text);
209 // make strings inside $ italic
210 $text = ereg_replace("\\$[^<>\n]+\\$", '<b><i>\\0</i></b>', $text);
213 /* Temporary fix for bad links in help messages. As a special case,
214 * XML-escaped metachars are de-escaped one level in the help message
215 * for legibility. Should be removed once we have completed a fully-html
216 * version of the help message. */
217 if ( $this->mUnescapeAmps )
218 $text = preg_replace( '/&amp;(amp|quot|lt|gt);/', '&\1;', $text );
220 return $text;
224 * Returns usage examples for this format.
226 protected function getExamples() {
227 return 'api.php?action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName();
230 public function getDescription() {
231 return $this->getIsHtml() ? ' (pretty-print in HTML)' : '';
234 public static function getBaseVersion() {
235 return __CLASS__ . ': $Id$';
240 * This printer is used to wrap an instance of the Feed class
241 * @ingroup API
243 class ApiFormatFeedWrapper extends ApiFormatBase {
245 public function __construct($main) {
246 parent :: __construct($main, 'feed');
250 * Call this method to initialize output data. See self::execute()
252 public static function setResult($result, $feed, $feedItems) {
253 // Store output in the Result data.
254 // This way we can check during execution if any error has occured
255 $data = & $result->getData();
256 $data['_feed'] = $feed;
257 $data['_feeditems'] = $feedItems;
261 * Feed does its own headers
263 public function getMimeType() {
264 return null;
268 * Optimization - no need to sanitize data that will not be needed
270 public function getNeedsRawData() {
271 return true;
275 * This class expects the result data to be in a custom format set by self::setResult()
276 * $result['_feed'] - an instance of one of the $wgFeedClasses classes
277 * $result['_feeditems'] - an array of FeedItem instances
279 public function execute() {
280 $data = $this->getResultData();
281 if (isset ($data['_feed']) && isset ($data['_feeditems'])) {
282 $feed = $data['_feed'];
283 $items = $data['_feeditems'];
285 $feed->outHeader();
286 foreach ($items as & $item)
287 $feed->outItem($item);
288 $feed->outFooter();
289 } else {
290 // Error has occured, print something useful
291 ApiBase::dieDebug( __METHOD__, 'Invalid feed class/item' );
295 public function getVersion() {
296 return __CLASS__ . ': $Id$';