Merge "test: new assertHTMLEquals()"
[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 //Set X-Frame-Options API results (bug 39180)
147 global $wgApiFrameOptions;
148 if ( $wgApiFrameOptions ) {
149 $this->getMain()->getRequest()->response()->header( "X-Frame-Options: $wgApiFrameOptions" );
150 }
151
152 if ( $isHtml ) {
153 ?>
154 <!DOCTYPE HTML>
155 <html>
156 <head>
157 <?php if ( $this->mUnescapeAmps ) {
158 ?> <title>MediaWiki API</title>
159 <?php } else {
160 ?> <title>MediaWiki API Result</title>
161 <?php } ?>
162 </head>
163 <body>
164 <?php
165
166
167 if ( !$isError ) {
168 ?>
169 <br />
170 <small>
171 You are looking at the HTML representation of the <?php echo( $this->mFormat ); ?> format.<br />
172 HTML is good for debugging, but is unsuitable for application use.<br />
173 Specify the format parameter to change the output format.<br />
174 To see the non HTML representation of the <?php echo( $this->mFormat ); ?> format, set format=<?php echo( strtolower( $this->mFormat ) ); ?>.<br />
175 See the <a href='https://www.mediawiki.org/wiki/API'>complete documentation</a>, or
176 <a href='<?php echo( $script ); ?>'>API help</a> for more information.
177 </small>
178 <?php
179
180
181 }
182 ?>
183 <pre>
184 <?php
185
186
187 }
188 }
189
190 /**
191 * Finish printing. Closes HTML tags.
192 */
193 public function closePrinter() {
194 if ( $this->mDisabled ) {
195 return;
196 }
197 if ( $this->getIsHtml() ) {
198 ?>
199
200 </pre>
201 </body>
202 </html>
203 <?php
204
205
206 }
207 }
208
209 /**
210 * The main format printing function. Call it to output the result
211 * string to the user. This function will automatically output HTML
212 * when format name ends in 'fm'.
213 * @param $text string
214 */
215 public function printText( $text ) {
216 if ( $this->mDisabled ) {
217 return;
218 }
219 if ( $this->mBufferResult ) {
220 $this->mBuffer = $text;
221 } elseif ( $this->getIsHtml() ) {
222 echo $this->formatHTML( $text );
223 } else {
224 // For non-HTML output, clear all errors that might have been
225 // displayed if display_errors=On
226 // Do this only once, of course
227 if ( !$this->mCleared ) {
228 ob_clean();
229 $this->mCleared = true;
230 }
231 echo $text;
232 }
233 }
234
235 /**
236 * Get the contents of the buffer.
237 */
238 public function getBuffer() {
239 return $this->mBuffer;
240 }
241
242 /**
243 * Set the flag to buffer the result instead of printing it.
244 * @param $value bool
245 */
246 public function setBufferResult( $value ) {
247 $this->mBufferResult = $value;
248 }
249
250 /**
251 * Sets whether the pretty-printer should format *bold* and $italics$
252 * @param $help bool
253 */
254 public function setHelp( $help = true ) {
255 $this->mHelp = $help;
256 }
257
258 /**
259 * Pretty-print various elements in HTML format, such as xml tags and
260 * URLs. This method also escapes characters like <
261 * @param $text string
262 * @return string
263 */
264 protected function formatHTML( $text ) {
265 // Escape everything first for full coverage
266 $text = htmlspecialchars( $text );
267
268 // encode all comments or tags as safe blue strings
269 $text = str_replace( '&lt;', '<span style="color:blue;">&lt;', $text );
270 $text = str_replace( '&gt;', '&gt;</span>', $text );
271 // identify URLs
272 $protos = wfUrlProtocolsWithoutProtRel();
273 // This regex hacks around bug 13218 (&quot; included in the URL)
274 $text = preg_replace( "#(((?i)$protos).*?)(&quot;)?([ \\'\"<>\n]|&lt;|&gt;|&quot;)#", '<a href="\\1">\\1</a>\\3\\4', $text );
275 // identify requests to api.php
276 $text = preg_replace( "#api\\.php\\?[^ <\n\t]+#", '<a href="\\0">\\0</a>', $text );
277 if ( $this->mHelp ) {
278 // make strings inside * bold
279 $text = preg_replace( "#\\*[^<>\n]+\\*#", '<b>\\0</b>', $text );
280 // make strings inside $ italic
281 $text = preg_replace( "#\\$[^<>\n]+\\$#", '<b><i>\\0</i></b>', $text );
282 }
283
284 /**
285 * Temporary fix for bad links in help messages. As a special case,
286 * XML-escaped metachars are de-escaped one level in the help message
287 * for legibility. Should be removed once we have completed a fully-HTML
288 * version of the help message.
289 */
290 if ( $this->mUnescapeAmps ) {
291 $text = preg_replace( '/&amp;(amp|quot|lt|gt);/', '&\1;', $text );
292 }
293
294 return $text;
295 }
296
297 public function getExamples() {
298 return array(
299 'api.php?action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName()
300 => "Format the query result in the {$this->getModuleName()} format",
301 );
302 }
303
304 public function getHelpUrls() {
305 return 'https://www.mediawiki.org/wiki/API:Data_formats';
306 }
307
308 public function getDescription() {
309 return $this->getIsHtml() ? ' (pretty-print in HTML)' : '';
310 }
311
312 public static function getBaseVersion() {
313 return __CLASS__ . ': $Id$';
314 }
315 }
316
317 /**
318 * This printer is used to wrap an instance of the Feed class
319 * @ingroup API
320 */
321 class ApiFormatFeedWrapper extends ApiFormatBase {
322
323 public function __construct( $main ) {
324 parent::__construct( $main, 'feed' );
325 }
326
327 /**
328 * Call this method to initialize output data. See execute()
329 * @param $result ApiResult
330 * @param $feed object an instance of one of the $wgFeedClasses classes
331 * @param $feedItems array of FeedItem objects
332 */
333 public static function setResult( $result, $feed, $feedItems ) {
334 // Store output in the Result data.
335 // This way we can check during execution if any error has occurred
336 // Disable size checking for this because we can't continue
337 // cleanly; size checking would cause more problems than it'd
338 // solve
339 $result->disableSizeCheck();
340 $result->addValue( null, '_feed', $feed );
341 $result->addValue( null, '_feeditems', $feedItems );
342 $result->enableSizeCheck();
343 }
344
345 /**
346 * Feed does its own headers
347 *
348 * @return null
349 */
350 public function getMimeType() {
351 return null;
352 }
353
354 /**
355 * Optimization - no need to sanitize data that will not be needed
356 *
357 * @return bool
358 */
359 public function getNeedsRawData() {
360 return true;
361 }
362
363 /**
364 * This class expects the result data to be in a custom format set by self::setResult()
365 * $result['_feed'] - an instance of one of the $wgFeedClasses classes
366 * $result['_feeditems'] - an array of FeedItem instances
367 */
368 public function execute() {
369 $data = $this->getResultData();
370 if ( isset( $data['_feed'] ) && isset( $data['_feeditems'] ) ) {
371 $feed = $data['_feed'];
372 $items = $data['_feeditems'];
373
374 $feed->outHeader();
375 foreach ( $items as & $item ) {
376 $feed->outItem( $item );
377 }
378 $feed->outFooter();
379 } else {
380 // Error has occurred, print something useful
381 ApiBase::dieDebug( __METHOD__, 'Invalid feed class/item' );
382 }
383 }
384
385 public function getVersion() {
386 return __CLASS__ . ': $Id$';
387 }
388 }