API: (bug 16422) Don't show help in format=jsonfm unless specifically requested with...
[lhc/web/wiklou.git] / includes / api / ApiFormatBase.php
1 <?php
2
3 /*
4 * Created on Sep 19, 2006
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9 *
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.
14 *
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.
19 *
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
24 */
25
26 if (!defined('MEDIAWIKI')) {
27 // Eclipse helper - will be ignored in production
28 require_once ('ApiBase.php');
29 }
30
31 /**
32 * This is the abstract base class for API formatters.
33 *
34 * @ingroup API
35 */
36 abstract class ApiFormatBase extends ApiBase {
37
38 private $mIsHtml, $mFormat, $mUnescapeAmps, $mHelp, $mCleared;
39
40 /**
41 * Constructor
42 * If $format ends with 'fm', pretty-print the output in HTML.
43 * @param $main ApiMain
44 * @param $format string Format name
45 */
46 public function __construct($main, $format) {
47 parent :: __construct($main, $format);
48
49 $this->mIsHtml = (substr($format, -2, 2) === 'fm'); // ends with 'fm'
50 if ($this->mIsHtml)
51 $this->mFormat = substr($format, 0, -2); // remove ending 'fm'
52 else
53 $this->mFormat = $format;
54 $this->mFormat = strtoupper($this->mFormat);
55 $this->mCleared = false;
56 }
57
58 /**
59 * Overriding class returns the mime type that should be sent to the client.
60 * This method is not called if getIsHtml() returns true.
61 * @return string
62 */
63 public abstract function getMimeType();
64
65 /**
66 * Whether this formatter needs raw data such as _element tags
67 * @return bool
68 */
69 public function getNeedsRawData() {
70 return false;
71 }
72
73 /**
74 * Get the internal format name
75 * @return string
76 */
77 public function getFormat() {
78 return $this->mFormat;
79 }
80
81 /**
82 * Specify whether or not sequences like &amp;quot; should be unescaped
83 * to &quot; . This should only be set to true for the help message
84 * when rendered in the default (xmlfm) format. This is a temporary
85 * special-case fix that should be removed once the help has been
86 * reworked to use a fully HTML interface.
87 *
88 * @param $b bool Whether or not ampersands should be escaped.
89 */
90 public function setUnescapeAmps ( $b ) {
91 $this->mUnescapeAmps = $b;
92 }
93
94 /**
95 * Returns true when the HTML pretty-printer should be used.
96 * The default implementation assumes that formats ending with 'fm'
97 * should be formatted in HTML.
98 * @return bool
99 */
100 public function getIsHtml() {
101 return $this->mIsHtml;
102 }
103
104 /**
105 * Whether this formatter can format the help message in a nice way.
106 * By default, this returns the same as getIsHtml().
107 * When action=help is set explicitly, the help will always be shown
108 * @return bool
109 */
110 public function getWantsHelp() {
111 return $this->getIsHtml();
112 }
113
114 /**
115 * Initialize the printer function and prepare the output headers, etc.
116 * This method must be the first outputing method during execution.
117 * A help screen's header is printed for the HTML-based output
118 * @param $isError bool Whether an error message is printed
119 */
120 function initPrinter($isError) {
121 $isHtml = $this->getIsHtml();
122 $mime = $isHtml ? 'text/html' : $this->getMimeType();
123 $script = wfScript( 'api' );
124
125 // Some printers (ex. Feed) do their own header settings,
126 // in which case $mime will be set to null
127 if (is_null($mime))
128 return; // skip any initialization
129
130 header("Content-Type: $mime; charset=utf-8");
131
132 if ($isHtml) {
133 ?>
134 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
135 <html>
136 <head>
137 <?php if ($this->mUnescapeAmps) {
138 ?> <title>MediaWiki API</title>
139 <?php } else {
140 ?> <title>MediaWiki API Result</title>
141 <?php } ?>
142 </head>
143 <body>
144 <?php
145
146
147 if( !$isError ) {
148 ?>
149 <br/>
150 <small>
151 You are looking at the HTML representation of the <?php echo( $this->mFormat ); ?> format.<br/>
152 HTML is good for debugging, but probably is not suitable for your application.<br/>
153 See <a href='http://www.mediawiki.org/wiki/API'>complete documentation</a>, or
154 <a href='<?php echo( $script ); ?>'>API help</a> for more information.
155 </small>
156 <?php
157
158
159 }
160 ?>
161 <pre>
162 <?php
163
164
165 }
166 }
167
168 /**
169 * Finish printing. Closes HTML tags.
170 */
171 public function closePrinter() {
172 if ($this->getIsHtml()) {
173 ?>
174
175 </pre>
176 </body>
177 </html>
178 <?php
179
180
181 }
182 }
183
184 /**
185 * The main format printing function. Call it to output the result
186 * string to the user. This function will automatically output HTML
187 * when format name ends in 'fm'.
188 * @param $text string
189 */
190 public function printText($text) {
191 if ($this->getIsHtml())
192 echo $this->formatHTML($text);
193 else
194 {
195 // For non-HTML output, clear all errors that might have been
196 // displayed if display_errors=On
197 // Do this only once, of course
198 if(!$this->mCleared)
199 {
200 ob_clean();
201 $this->mCleared = true;
202 }
203 echo $text;
204 }
205 }
206
207 /**
208 * Sets whether the pretty-printer should format *bold* and $italics$
209 * @param $help bool
210 */
211 public function setHelp( $help = true ) {
212 $this->mHelp = true;
213 }
214
215 /**
216 * Prety-print various elements in HTML format, such as xml tags and
217 * URLs. This method also escapes characters like <
218 * @param $text string
219 * @return string
220 */
221 protected function formatHTML($text) {
222 global $wgUrlProtocols;
223
224 // Escape everything first for full coverage
225 $text = htmlspecialchars($text);
226
227 // encode all comments or tags as safe blue strings
228 $text = preg_replace('/\&lt;(!--.*?--|.*?)\&gt;/', '<span style="color:blue;">&lt;\1&gt;</span>', $text);
229 // identify URLs
230 $protos = implode("|", $wgUrlProtocols);
231 # This regex hacks around bug 13218 (&quot; included in the URL)
232 $text = preg_replace("#(($protos).*?)(&quot;)?([ \\'\"<>\n]|&lt;|&gt;|&quot;)#", '<a href="\\1">\\1</a>\\3\\4', $text);
233 // identify requests to api.php
234 $text = preg_replace("#api\\.php\\?[^ \\()<\n\t]+#", '<a href="\\0">\\0</a>', $text);
235 if( $this->mHelp ) {
236 // make strings inside * bold
237 $text = preg_replace("#\\*[^<>\n]+\\*#", '<b>\\0</b>', $text);
238 // make strings inside $ italic
239 $text = preg_replace("#\\$[^<>\n]+\\$#", '<b><i>\\0</i></b>', $text);
240 }
241
242 /* Temporary fix for bad links in help messages. As a special case,
243 * XML-escaped metachars are de-escaped one level in the help message
244 * for legibility. Should be removed once we have completed a fully-html
245 * version of the help message. */
246 if ( $this->mUnescapeAmps )
247 $text = preg_replace( '/&amp;(amp|quot|lt|gt);/', '&\1;', $text );
248
249 return $text;
250 }
251
252 protected function getExamples() {
253 return 'api.php?action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName();
254 }
255
256 public function getDescription() {
257 return $this->getIsHtml() ? ' (pretty-print in HTML)' : '';
258 }
259
260 public static function getBaseVersion() {
261 return __CLASS__ . ': $Id$';
262 }
263 }
264
265 /**
266 * This printer is used to wrap an instance of the Feed class
267 * @ingroup API
268 */
269 class ApiFormatFeedWrapper extends ApiFormatBase {
270
271 public function __construct($main) {
272 parent :: __construct($main, 'feed');
273 }
274
275 /**
276 * Call this method to initialize output data. See execute()
277 * @param $result ApiResult
278 * @param $feed object an instance of one of the $wgFeedClasses classes
279 * @param $feedItems array of FeedItem objects
280 */
281 public static function setResult($result, $feed, $feedItems) {
282 // Store output in the Result data.
283 // This way we can check during execution if any error has occured
284 // Disable size checking for this because we can't continue
285 // cleanly; size checking would cause more problems than it'd
286 // solve
287 $result->disableSizeCheck();
288 $result->addValue(null, '_feed', $feed);
289 $result->addValue(null, '_feeditems', $feedItems);
290 $result->enableSizeCheck();
291 }
292
293 /**
294 * Feed does its own headers
295 */
296 public function getMimeType() {
297 return null;
298 }
299
300 /**
301 * Optimization - no need to sanitize data that will not be needed
302 */
303 public function getNeedsRawData() {
304 return true;
305 }
306
307 /**
308 * This class expects the result data to be in a custom format set by self::setResult()
309 * $result['_feed'] - an instance of one of the $wgFeedClasses classes
310 * $result['_feeditems'] - an array of FeedItem instances
311 */
312 public function execute() {
313 $data = $this->getResultData();
314 if (isset ($data['_feed']) && isset ($data['_feeditems'])) {
315 $feed = $data['_feed'];
316 $items = $data['_feeditems'];
317
318 $feed->outHeader();
319 foreach ($items as & $item)
320 $feed->outItem($item);
321 $feed->outFooter();
322 } else {
323 // Error has occured, print something useful
324 ApiBase::dieDebug( __METHOD__, 'Invalid feed class/item' );
325 }
326 }
327
328 public function getVersion() {
329 return __CLASS__ . ': $Id$';
330 }
331 }