Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / parser / MWTidy.php
blobd446ccf66cf7ec0132b4f566a08d902d793a19f1
1 <?php
2 /**
3 * HTML validation and correction
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.
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.
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
20 * @file
21 * @ingroup Parser
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
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.
34 * @ingroup Parser
36 class MWTidyWrapper {
38 /**
39 * @var ReplacementArray
41 protected $mTokens;
43 protected $mUniqPrefix;
45 protected $mMarkerIndex;
47 public function __construct() {
48 $this->mTokens = null;
49 $this->mUniqPrefix = null;
52 /**
53 * @param string $text
54 * @return string
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;
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 );
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>';
80 return $wrappedtext;
83 /**
84 * @param array $m
86 * @return string
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;
95 /**
96 * @param string $text
97 * @return string
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 );
103 // Restore the contents of placeholder tokens
104 $text = $this->mTokens->replace( $text );
106 return $text;
112 * Class to interact with HTML tidy
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.
118 * @ingroup Parser
120 class MWTidy {
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.
126 * @param string $text Hideous HTML input
127 * @return string Corrected HTML output
129 public static function tidy( $text ) {
130 $wrapper = new MWTidyWrapper;
131 $wrappedtext = $wrapper->getWrapped( $text );
133 $retVal = null;
134 $correctedtext = self::clean( $wrappedtext, false, $retVal );
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";
144 $correctedtext = $wrapper->postprocess( $correctedtext ); // restore any hidden tokens
146 return $correctedtext;
150 * Check HTML for errors, used if $wgValidateAllHtml = true.
152 * @param string $text
153 * @param string &$errorStr Return the error string
154 * @return bool Whether the HTML is valid
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;
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
170 private static function clean( $text, $stderr = false, &$retval = null ) {
171 global $wgTidyInternal;
173 if ( $wgTidyInternal ) {
174 if ( wfIsHHVM() ) {
175 if ( $stderr ) {
176 throw new MWException( __METHOD__ . ": error text return from HHVM tidy is not supported" );
178 return self::hhvmClean( $text, $retval );
179 } else {
180 return self::phpClean( $text, $stderr, $retval );
182 } else {
183 return self::externalClean( $text, $stderr, $retval );
188 * Spawn an external HTML tidy process and get corrected markup back from it.
189 * Also called in OutputHandler.php for full page validation
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
196 private static function externalClean( $text, $stderr = false, &$retval = null ) {
197 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
199 $cleansource = '';
200 $opts = ' -utf8';
202 if ( $stderr ) {
203 $descriptorspec = array(
204 0 => array( 'pipe', 'r' ),
205 1 => array( 'file', wfGetNull(), 'a' ),
206 2 => array( 'pipe', 'w' )
208 } else {
209 $descriptorspec = array(
210 0 => array( 'pipe', 'r' ),
211 1 => array( 'pipe', 'w' ),
212 2 => array( 'file', wfGetNull(), 'a' )
216 $readpipe = $stderr ? 2 : 1;
217 $pipes = array();
219 $process = proc_open(
220 "$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes );
222 //NOTE: At least on linux, the process will be created even if tidy is not installed.
223 // This means that missing tidy will be treated as a validation failure.
225 if ( is_resource( $process ) ) {
226 // Theoretically, this style of communication could cause a deadlock
227 // here. If the stdout buffer fills up, then writes to stdin could
228 // block. This doesn't appear to happen with tidy, because tidy only
229 // writes to stdout after it's finished reading from stdin. Search
230 // for tidyParseStdin and tidySaveStdout in console/tidy.c
231 fwrite( $pipes[0], $text );
232 fclose( $pipes[0] );
233 while ( !feof( $pipes[$readpipe] ) ) {
234 $cleansource .= fgets( $pipes[$readpipe], 1024 );
236 fclose( $pipes[$readpipe] );
237 $retval = proc_close( $process );
238 } else {
239 wfWarn( "Unable to start external tidy process" );
240 $retval = -1;
243 if ( !$stderr && $cleansource == '' && $text != '' ) {
244 // Some kind of error happened, so we couldn't get the corrected text.
245 // Just give up; we'll use the source text and append a warning.
246 $cleansource = null;
249 return $cleansource;
253 * Use the HTML tidy extension to use the tidy library in-process,
254 * saving the overhead of spawning a new process.
256 * @param string $text HTML to check
257 * @param bool $stderr Whether to read result from error status instead of output
258 * @param int &$retval Exit code (-1 on internal error)
259 * @return string|null
261 private static function phpClean( $text, $stderr = false, &$retval = null ) {
262 global $wgTidyConf, $wgDebugTidy;
264 if ( ( !wfIsHHVM() && !class_exists( 'tidy' ) ) ||
265 ( wfIsHHVM() && !function_exists( 'tidy_repair_string' ) )
267 wfWarn( "Unable to load internal tidy class." );
268 $retval = -1;
270 return null;
273 $tidy = new tidy;
274 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
276 if ( $stderr ) {
277 $retval = $tidy->getStatus();
278 return $tidy->errorBuffer;
281 $tidy->cleanRepair();
282 $retval = $tidy->getStatus();
283 if ( $retval == 2 ) {
284 // 2 is magic number for fatal error
285 // http://www.php.net/manual/en/function.tidy-get-status.php
286 $cleansource = null;
287 } else {
288 $cleansource = tidy_get_output( $tidy );
289 if ( $wgDebugTidy && $retval > 0 ) {
290 $cleansource .= "<!--\nTidy reports:\n" .
291 str_replace( '-->', '--&gt;', $tidy->errorBuffer ) .
292 "\n-->";
296 return $cleansource;
300 * Use the tidy extension for HHVM from
301 * https://github.com/wikimedia/mediawiki-php-tidy
303 * This currently does not support the object-oriented interface, but
304 * tidy_repair_string() can be used for the most common tasks.
306 * @param string $text HTML to check
307 * @param int &$retval Exit code (-1 on internal error)
308 * @return string|null
310 private static function hhvmClean( $text, &$retval ) {
311 global $wgTidyConf;
313 $cleansource = tidy_repair_string( $text, $wgTidyConf, 'utf8' );
314 if ( $cleansource === false ) {
315 $cleansource = null;
316 $retval = -1;
317 } else {
318 $retval = 0;
321 return $cleansource;