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