Add lots of @throws
[lhc/web/wiklou.git] / includes / parser / MWTidy.php
1 <?php
2 /**
3 * HTML validation and correction
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Parser
22 */
23
24 /**
25 * Class used to hide mw:editsection tokens from Tidy so that it doesn't break them
26 * or break on them. This is a bit of a hack for now, but hopefully in the future
27 * we may create a real postprocessor or something that will replace this.
28 * It's called wrapper because for now it basically takes over MWTidy::tidy's task
29 * of wrapping the text in a xhtml block
30 *
31 * This re-uses some of the parser's UNIQ tricks, though some of it is private so it's
32 * duplicated. Perhaps we should create an abstract marker hiding class.
33 *
34 * @ingroup Parser
35 */
36 class MWTidyWrapper {
37
38 /**
39 * @var ReplacementArray
40 */
41 protected $mTokens;
42
43 protected $mUniqPrefix;
44
45 protected $mMarkerIndex;
46
47 public function __construct() {
48 $this->mTokens = null;
49 $this->mUniqPrefix = null;
50 }
51
52 /**
53 * @param string $text
54 * @return string
55 */
56 public function getWrapped( $text ) {
57 $this->mTokens = new ReplacementArray;
58 $this->mUniqPrefix = "\x7fUNIQ" .
59 dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
60 $this->mMarkerIndex = 0;
61
62 // Replace <mw:editsection> elements with placeholders
63 $wrappedtext = preg_replace_callback( ParserOutput::EDITSECTION_REGEX,
64 array( &$this, 'replaceCallback' ), $text );
65 // ...and <mw:toc> markers
66 $wrappedtext = preg_replace_callback( '/\<\\/?mw:toc\>/',
67 array( &$this, 'replaceCallback' ), $wrappedtext );
68 // ... and <math> tags
69 $wrappedtext = preg_replace_callback( '/\<math(.*?)\<\\/math\>/s',
70 array( &$this, 'replaceCallback' ), $wrappedtext );
71 // Modify inline Microdata <link> and <meta> elements so they say <html-link> and <html-meta> so
72 // we can trick Tidy into not stripping them out by including them in tidy's new-empty-tags config
73 $wrappedtext = preg_replace( '!<(link|meta)([^>]*?)(/{0,1}>)!', '<html-$1$2$3', $wrappedtext );
74
75 // Wrap the whole thing in a doctype and body for Tidy.
76 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' .
77 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>' .
78 '<head><title>test</title></head><body>' . $wrappedtext . '</body></html>';
79
80 return $wrappedtext;
81 }
82
83 /**
84 * @param array $m
85 *
86 * @return string
87 */
88 public function replaceCallback( $m ) {
89 $marker = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}" . Parser::MARKER_SUFFIX;
90 $this->mMarkerIndex++;
91 $this->mTokens->setPair( $marker, $m[0] );
92 return $marker;
93 }
94
95 /**
96 * @param string $text
97 * @return string
98 */
99 public function postprocess( $text ) {
100 // Revert <html-{link,meta}> back to <{link,meta}>
101 $text = preg_replace( '!<html-(link|meta)([^>]*?)(/{0,1}>)!', '<$1$2$3', $text );
102
103 // Restore the contents of placeholder tokens
104 $text = $this->mTokens->replace( $text );
105
106 return $text;
107 }
108
109 }
110
111 /**
112 * Class to interact with HTML tidy
113 *
114 * Either the external tidy program or the in-process tidy extension
115 * will be used depending on availability. Override the default
116 * $wgTidyInternal setting to disable the internal if it's not working.
117 *
118 * @ingroup Parser
119 */
120 class MWTidy {
121 /**
122 * Interface with html tidy, used if $wgUseTidy = true.
123 * If tidy isn't able to correct the markup, the original will be
124 * returned in all its glory with a warning comment appended.
125 *
126 * @param string $text Hideous HTML input
127 * @return string Corrected HTML output
128 */
129 public static function tidy( $text ) {
130 $wrapper = new MWTidyWrapper;
131 $wrappedtext = $wrapper->getWrapped( $text );
132
133 $retVal = null;
134 $correctedtext = self::clean( $wrappedtext, false, $retVal );
135
136 if ( $retVal < 0 ) {
137 wfDebug( "Possible tidy configuration error!\n" );
138 return $text . "\n<!-- Tidy was unable to run -->\n";
139 } elseif ( is_null( $correctedtext ) ) {
140 wfDebug( "Tidy error detected!\n" );
141 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
142 }
143
144 $correctedtext = $wrapper->postprocess( $correctedtext ); // restore any hidden tokens
145
146 return $correctedtext;
147 }
148
149 /**
150 * Check HTML for errors, used if $wgValidateAllHtml = true.
151 *
152 * @param string $text
153 * @param string &$errorStr Return the error string
154 * @return bool Whether the HTML is valid
155 */
156 public static function checkErrors( $text, &$errorStr = null ) {
157 $retval = 0;
158 $errorStr = self::clean( $text, true, $retval );
159 return ( $retval < 0 && $errorStr == '' ) || $retval == 0;
160 }
161
162 /**
163 * Perform a clean/repair operation
164 * @param string $text HTML to check
165 * @param bool $stderr Whether to read result from STDERR rather than STDOUT
166 * @param int &$retval Exit code (-1 on internal error)
167 * @return null|string
168 * @throws MWException
169 */
170 private static function clean( $text, $stderr = false, &$retval = null ) {
171 global $wgTidyInternal;
172
173 if ( $wgTidyInternal ) {
174 if ( wfIsHHVM() ) {
175 if ( $stderr ) {
176 throw new MWException( __METHOD__ . ": error text return from HHVM tidy is not supported" );
177 }
178 return self::hhvmClean( $text, $retval );
179 } else {
180 return self::phpClean( $text, $stderr, $retval );
181 }
182 } else {
183 return self::externalClean( $text, $stderr, $retval );
184 }
185 }
186
187 /**
188 * Spawn an external HTML tidy process and get corrected markup back from it.
189 * Also called in OutputHandler.php for full page validation
190 *
191 * @param string $text HTML to check
192 * @param bool $stderr Whether to read result from STDERR rather than STDOUT
193 * @param int &$retval Exit code (-1 on internal error)
194 * @return string|null
195 */
196 private static function externalClean( $text, $stderr = false, &$retval = null ) {
197 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
198 wfProfileIn( __METHOD__ );
199
200 $cleansource = '';
201 $opts = ' -utf8';
202
203 if ( $stderr ) {
204 $descriptorspec = array(
205 0 => array( 'pipe', 'r' ),
206 1 => array( 'file', wfGetNull(), 'a' ),
207 2 => array( 'pipe', 'w' )
208 );
209 } else {
210 $descriptorspec = array(
211 0 => array( 'pipe', 'r' ),
212 1 => array( 'pipe', 'w' ),
213 2 => array( 'file', wfGetNull(), 'a' )
214 );
215 }
216
217 $readpipe = $stderr ? 2 : 1;
218 $pipes = array();
219
220 $process = proc_open(
221 "$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes );
222
223 //NOTE: At least on linux, the process will be created even if tidy is not installed.
224 // This means that missing tidy will be treated as a validation failure.
225
226 if ( is_resource( $process ) ) {
227 // Theoretically, this style of communication could cause a deadlock
228 // here. If the stdout buffer fills up, then writes to stdin could
229 // block. This doesn't appear to happen with tidy, because tidy only
230 // writes to stdout after it's finished reading from stdin. Search
231 // for tidyParseStdin and tidySaveStdout in console/tidy.c
232 fwrite( $pipes[0], $text );
233 fclose( $pipes[0] );
234 while ( !feof( $pipes[$readpipe] ) ) {
235 $cleansource .= fgets( $pipes[$readpipe], 1024 );
236 }
237 fclose( $pipes[$readpipe] );
238 $retval = proc_close( $process );
239 } else {
240 wfWarn( "Unable to start external tidy process" );
241 $retval = -1;
242 }
243
244 if ( !$stderr && $cleansource == '' && $text != '' ) {
245 // Some kind of error happened, so we couldn't get the corrected text.
246 // Just give up; we'll use the source text and append a warning.
247 $cleansource = null;
248 }
249
250 wfProfileOut( __METHOD__ );
251 return $cleansource;
252 }
253
254 /**
255 * Use the HTML tidy extension to use the tidy library in-process,
256 * saving the overhead of spawning a new process.
257 *
258 * @param string $text HTML to check
259 * @param bool $stderr Whether to read result from error status instead of output
260 * @param int &$retval Exit code (-1 on internal error)
261 * @return string|null
262 */
263 private static function phpClean( $text, $stderr = false, &$retval = null ) {
264 global $wgTidyConf, $wgDebugTidy;
265 wfProfileIn( __METHOD__ );
266
267 if ( ( !wfIsHHVM() && !class_exists( 'tidy' ) ) ||
268 ( wfIsHHVM() && !function_exists( 'tidy_repair_string' ) )
269 ) {
270 wfWarn( "Unable to load internal tidy class." );
271 $retval = -1;
272
273 wfProfileOut( __METHOD__ );
274 return null;
275 }
276
277 $tidy = new tidy;
278 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
279
280 if ( $stderr ) {
281 $retval = $tidy->getStatus();
282
283 wfProfileOut( __METHOD__ );
284 return $tidy->errorBuffer;
285 }
286
287 $tidy->cleanRepair();
288 $retval = $tidy->getStatus();
289 if ( $retval == 2 ) {
290 // 2 is magic number for fatal error
291 // http://www.php.net/manual/en/function.tidy-get-status.php
292 $cleansource = null;
293 } else {
294 $cleansource = tidy_get_output( $tidy );
295 if ( $wgDebugTidy && $retval > 0 ) {
296 $cleansource .= "<!--\nTidy reports:\n" .
297 str_replace( '-->', '--&gt;', $tidy->errorBuffer ) .
298 "\n-->";
299 }
300 }
301
302 wfProfileOut( __METHOD__ );
303 return $cleansource;
304 }
305
306 /**
307 * Use the tidy extension for HHVM from
308 * https://github.com/wikimedia/mediawiki-php-tidy
309 *
310 * This currently does not support the object-oriented interface, but
311 * tidy_repair_string() can be used for the most common tasks.
312 *
313 * @param string $text HTML to check
314 * @param int &$retval Exit code (-1 on internal error)
315 * @return string|null
316 */
317 private static function hhvmClean( $text, &$retval ) {
318 global $wgTidyConf;
319 wfProfileIn( __METHOD__ );
320 $cleansource = tidy_repair_string( $text, $wgTidyConf, 'utf8' );
321 if ( $cleansource === false ) {
322 $cleansource = null;
323 $retval = -1;
324 } else {
325 $retval = 0;
326 }
327 wfProfileOut( __METHOD__ );
328 return $cleansource;
329 }
330 }