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