API: (bug 17182) Fix pretty printer so URLs with parentheses in them are autolinked...
[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 * 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 $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 * 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.
67 */
68 public function getNeedsRawData() {
69 return false;
70 }
71
72 /**
73 * Get the internal format name
74 */
75 public function getFormat() {
76 return $this->mFormat;
77 }
78
79 /**
80 * Specify whether or not ampersands should be escaped to '&amp;' when rendering. This
81 * should only be set to true for the help message when rendered in the default (xmlfm)
82 * format. This is a temporary special-case fix that should be removed once the help
83 * has been reworked to use a fully html interface.
84 *
85 * @param boolean Whether or not ampersands should be escaped.
86 */
87 public function setUnescapeAmps ( $b ) {
88 $this->mUnescapeAmps = $b;
89 }
90
91 /**
92 * Returns true when an HTML filtering printer should be used.
93 * The default implementation assumes that formats ending with 'fm'
94 * should be formatted in HTML.
95 */
96 public function getIsHtml() {
97 return $this->mIsHtml;
98 }
99
100 /**
101 * Initialize the printer function and prepares the output headers, etc.
102 * This method must be the first outputing method during execution.
103 * A help screen's header is printed for the HTML-based output
104 */
105 function initPrinter($isError) {
106 $isHtml = $this->getIsHtml();
107 $mime = $isHtml ? 'text/html' : $this->getMimeType();
108 $script = wfScript( 'api' );
109
110 // Some printers (ex. Feed) do their own header settings,
111 // in which case $mime will be set to null
112 if (is_null($mime))
113 return; // skip any initialization
114
115 header("Content-Type: $mime; charset=utf-8");
116
117 if ($isHtml) {
118 ?>
119 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
120 <html>
121 <head>
122 <?php if ($this->mUnescapeAmps) {
123 ?> <title>MediaWiki API</title>
124 <?php } else {
125 ?> <title>MediaWiki API Result</title>
126 <?php } ?>
127 </head>
128 <body>
129 <?php
130
131
132 if( !$isError ) {
133 ?>
134 <br/>
135 <small>
136 You are looking at the HTML representation of the <?php echo( $this->mFormat ); ?> format.<br/>
137 HTML is good for debugging, but probably is not suitable for your application.<br/>
138 See <a href='http://www.mediawiki.org/wiki/API'>complete documentation</a>, or
139 <a href='<?php echo( $script ); ?>'>API help</a> for more information.
140 </small>
141 <?php
142
143
144 }
145 ?>
146 <pre>
147 <?php
148
149
150 }
151 }
152
153 /**
154 * Finish printing. Closes HTML tags.
155 */
156 public function closePrinter() {
157 if ($this->getIsHtml()) {
158 ?>
159
160 </pre>
161 </body>
162 </html>
163 <?php
164
165
166 }
167 }
168
169 /**
170 * The main format printing function. Call it to output the result string to the user.
171 * This function will automatically output HTML when format name ends in 'fm'.
172 */
173 public function printText($text) {
174 if ($this->getIsHtml())
175 echo $this->formatHTML($text);
176 else
177 {
178 // For non-HTML output, clear all errors that might have been
179 // displayed if display_errors=On
180 // Do this only once, of course
181 if(!$this->mCleared)
182 {
183 ob_clean();
184 $this->mCleared = true;
185 }
186 echo $text;
187 }
188 }
189
190 /**
191 * Says pretty-printer that it should use *bold* and $italics$ formatting
192 */
193 public function setHelp( $help = true ) {
194 $this->mHelp = true;
195 }
196
197 /**
198 * Prety-print various elements in HTML format, such as xml tags and URLs.
199 * This method also replaces any '<' with &lt;
200 */
201 protected function formatHTML($text) {
202 global $wgUrlProtocols;
203
204 // Escape everything first for full coverage
205 $text = htmlspecialchars($text);
206
207 // encode all comments or tags as safe blue strings
208 $text = preg_replace('/\&lt;(!--.*?--|.*?)\&gt;/', '<span style="color:blue;">&lt;\1&gt;</span>', $text);
209 // identify URLs
210 $protos = implode("|", $wgUrlProtocols);
211 # This regex hacks around bug 13218 (&quot; included in the URL)
212 $text = preg_replace("#(($protos).*?)(&quot;)?([ \\'\"<\n])#", '<a href="\\1">\\1</a>\\3\\4', $text);
213 // identify requests to api.php
214 $text = preg_replace("#api\\.php\\?[^ \\()<\n\t]+#", '<a href="\\0">\\0</a>', $text);
215 if( $this->mHelp ) {
216 // make strings inside * bold
217 $text = ereg_replace("\\*[^<>\n]+\\*", '<b>\\0</b>', $text);
218 // make strings inside $ italic
219 $text = ereg_replace("\\$[^<>\n]+\\$", '<b><i>\\0</i></b>', $text);
220 }
221
222 /* Temporary fix for bad links in help messages. As a special case,
223 * XML-escaped metachars are de-escaped one level in the help message
224 * for legibility. Should be removed once we have completed a fully-html
225 * version of the help message. */
226 if ( $this->mUnescapeAmps )
227 $text = preg_replace( '/&amp;(amp|quot|lt|gt);/', '&\1;', $text );
228
229 return $text;
230 }
231
232 /**
233 * Returns usage examples for this format.
234 */
235 protected function getExamples() {
236 return 'api.php?action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName();
237 }
238
239 public function getDescription() {
240 return $this->getIsHtml() ? ' (pretty-print in HTML)' : '';
241 }
242
243 public static function getBaseVersion() {
244 return __CLASS__ . ': $Id$';
245 }
246 }
247
248 /**
249 * This printer is used to wrap an instance of the Feed class
250 * @ingroup API
251 */
252 class ApiFormatFeedWrapper extends ApiFormatBase {
253
254 public function __construct($main) {
255 parent :: __construct($main, 'feed');
256 }
257
258 /**
259 * Call this method to initialize output data. See self::execute()
260 */
261 public static function setResult($result, $feed, $feedItems) {
262 // Store output in the Result data.
263 // This way we can check during execution if any error has occured
264 $data = & $result->getData();
265 $data['_feed'] = $feed;
266 $data['_feeditems'] = $feedItems;
267 }
268
269 /**
270 * Feed does its own headers
271 */
272 public function getMimeType() {
273 return null;
274 }
275
276 /**
277 * Optimization - no need to sanitize data that will not be needed
278 */
279 public function getNeedsRawData() {
280 return true;
281 }
282
283 /**
284 * This class expects the result data to be in a custom format set by self::setResult()
285 * $result['_feed'] - an instance of one of the $wgFeedClasses classes
286 * $result['_feeditems'] - an array of FeedItem instances
287 */
288 public function execute() {
289 $data = $this->getResultData();
290 if (isset ($data['_feed']) && isset ($data['_feeditems'])) {
291 $feed = $data['_feed'];
292 $items = $data['_feeditems'];
293
294 $feed->outHeader();
295 foreach ($items as & $item)
296 $feed->outItem($item);
297 $feed->outFooter();
298 } else {
299 // Error has occured, print something useful
300 ApiBase::dieDebug( __METHOD__, 'Invalid feed class/item' );
301 }
302 }
303
304 public function getVersion() {
305 return __CLASS__ . ': $Id$';
306 }
307 }