(bug 11632) API: Breaking change: Specify the type of a change in the recentchanges...
[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 * @addtogroup API
35 */
36 abstract class ApiFormatBase extends ApiBase {
37
38 private $mIsHtml, $mFormat, $mUnescapeAmps;
39
40 /**
41 * Create a new instance of the formatter.
42 * If the format name ends with 'fm', wrap its output in the proper HTML.
43 */
44 public function __construct($main, $format) {
45 parent :: __construct($main, $format);
46
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 }
54
55 /**
56 * Overriding class returns the mime type that should be sent to the client.
57 * This method is not called if getIsHtml() returns true.
58 * @return string
59 */
60 public abstract function getMimeType();
61
62 /**
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.
66 */
67 public function getNeedsRawData() {
68 return false;
69 }
70
71 /**
72 * Specify whether or not ampersands should be escaped to '&amp;' 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.
76 *
77 * @param boolean Whether or not ampersands should be escaped.
78 */
79 public function setUnescapeAmps ( $b ) {
80 $this->mUnescapeAmps = $b;
81 }
82
83 /**
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.
87 */
88 public function getIsHtml() {
89 return $this->mIsHtml;
90 }
91
92 /**
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
96 */
97 function initPrinter($isError) {
98 $isHtml = $this->getIsHtml();
99 $mime = $isHtml ? 'text/html' : $this->getMimeType();
100 $script = wfScript( 'api' );
101
102 // Some printers (ex. Feed) do their own header settings,
103 // in which case $mime will be set to null
104 if (is_null($mime))
105 return; // skip any initialization
106
107 header("Content-Type: $mime; charset=utf-8");
108
109 if ($isHtml) {
110 ?>
111 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
112 <html>
113 <head>
114 <title>MediaWiki API</title>
115 </head>
116 <body>
117 <?php
118
119
120 if( !$isError ) {
121 ?>
122 <br/>
123 <small>
124 You are looking at the HTML representation of the <?php echo( $this->mFormat ); ?> format.<br/>
125 HTML is good for debugging, but probably is not suitable for your application.<br/>
126 See <a href='http://www.mediawiki.org/wiki/API'>complete documentation</a>, or
127 <a href='<?php echo( $script ); ?>'>API help</a> for more information.
128 </small>
129 <?php
130
131
132 }
133 ?>
134 <pre>
135 <?php
136
137
138 }
139 }
140
141 /**
142 * Finish printing. Closes HTML tags.
143 */
144 public function closePrinter() {
145 if ($this->getIsHtml()) {
146 ?>
147
148 </pre>
149 </body>
150 </html>
151 <?php
152
153
154 }
155 }
156
157 /**
158 * The main format printing function. Call it to output the result string to the user.
159 * This function will automatically output HTML when format name ends in 'fm'.
160 */
161 public function printText($text) {
162 if ($this->getIsHtml())
163 echo $this->formatHTML($text);
164 else
165 echo $text;
166 }
167
168 /**
169 * Prety-print various elements in HTML format, such as xml tags and URLs.
170 * This method also replaces any '<' with &lt;
171 */
172 protected function formatHTML($text) {
173 // Escape everything first for full coverage
174 $text = htmlspecialchars($text);
175
176 // encode all comments or tags as safe blue strings
177 $text = preg_replace('/\&lt;(!--.*?--|.*?)\&gt;/', '<span style="color:blue;">&lt;\1&gt;</span>', $text);
178 // identify URLs
179 $protos = "http|https|ftp|gopher";
180 $text = ereg_replace("($protos)://[^ \\'\"()<\n]+", '<a href="\\0">\\0</a>', $text);
181 // identify requests to api.php
182 $text = ereg_replace("api\\.php\\?[^ \\()<\n\t]+", '<a href="\\0">\\0</a>', $text);
183 // make strings inside * bold
184 $text = ereg_replace("\\*[^<>\n]+\\*", '<b>\\0</b>', $text);
185 // make strings inside $ italic
186 $text = ereg_replace("\\$[^<>\n]+\\$", '<b><i>\\0</i></b>', $text);
187
188 /* Temporary fix for bad links in help messages. As a special case,
189 * XML-escaped metachars are de-escaped one level in the help message
190 * for legibility. Should be removed once we have completed a fully-html
191 * version of the help message. */
192 if ( $this->mUnescapeAmps )
193 $text = preg_replace( '/&amp;(amp|quot|lt|gt);/', '&\1;', $text );
194
195 return $text;
196 }
197
198 /**
199 * Returns usage examples for this format.
200 */
201 protected function getExamples() {
202 return 'api.php?action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName();
203 }
204
205 protected function getDescription() {
206 return $this->getIsHtml() ? ' (pretty-print in HTML)' : '';
207 }
208
209 public static function getBaseVersion() {
210 return __CLASS__ . ': $Id$';
211 }
212 }
213
214 /**
215 * This printer is used to wrap an instance of the Feed class
216 * @addtogroup API
217 */
218 class ApiFormatFeedWrapper extends ApiFormatBase {
219
220 public function __construct($main) {
221 parent :: __construct($main, 'feed');
222 }
223
224 /**
225 * Call this method to initialize output data. See self::execute()
226 */
227 public static function setResult($result, $feed, $feedItems) {
228 // Store output in the Result data.
229 // This way we can check during execution if any error has occured
230 $data = & $result->getData();
231 $data['_feed'] = $feed;
232 $data['_feeditems'] = $feedItems;
233 }
234
235 /**
236 * Feed does its own headers
237 */
238 public function getMimeType() {
239 return null;
240 }
241
242 /**
243 * Optimization - no need to sanitize data that will not be needed
244 */
245 public function getNeedsRawData() {
246 return true;
247 }
248
249 /**
250 * This class expects the result data to be in a custom format set by self::setResult()
251 * $result['_feed'] - an instance of one of the $wgFeedClasses classes
252 * $result['_feeditems'] - an array of FeedItem instances
253 */
254 public function execute() {
255 $data = $this->getResultData();
256 if (isset ($data['_feed']) && isset ($data['_feeditems'])) {
257 $feed = $data['_feed'];
258 $items = $data['_feeditems'];
259
260 $feed->outHeader();
261 foreach ($items as & $item)
262 $feed->outItem($item);
263 $feed->outFooter();
264 } else {
265 // Error has occured, print something usefull
266 // TODO: make this error more informative using ApiBase :: dieDebug() or similar
267 wfHttpError(500, 'Internal Server Error', '');
268 }
269 }
270
271 public function getVersion() {
272 return __CLASS__ . ': $Id$';
273 }
274 }