Follow up to r89419:
[mediawiki.git] / includes / parser / Tidy.php
blobe434db782b38c0de9f673522c2c06982d73642a1
1 <?php
2 /**
3 * HTML validation and correction
5 * @file
6 */
8 /**
9 * Class used to hide mw:editsection tokens from Tidy so that it doesn't break them
10 * or break on them. This is a bit of a hack for now, but hopefully in the future
11 * we may create a real postprocessor or something that will replace this.
12 * It's called wrapper because for now it basically takes over MWTidy::tidy's task
13 * of wrapping the text in a xhtml block
15 * This re-uses some of the parser's UNIQ tricks, though some of it is private so it's
16 * duplicated. Perhaps we should create an abstract marker hiding class.
18 class MWTidyWrapper {
20 /**
21 * @var ReplacementArray
23 protected $mTokens;
25 protected $mUniqPrefix;
27 protected $mMarkerIndex;
29 public function __construct() {
30 $this->mTokens = null;
31 $this->mUniqPrefix = null;
34 /**
35 * @param $text string
36 * @return string
38 public function getWrapped( $text ) {
39 $this->mTokens = new ReplacementArray;
40 $this->mUniqPrefix = "\x7fUNIQ" .
41 dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
42 $this->mMarkerIndex = 0;
43 $wrappedtext = preg_replace_callback( ParserOutput::EDITSECTION_REGEX,
44 array( &$this, 'replaceEditSectionLinksCallback' ), $text );
46 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
47 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
48 '<head><title>test</title></head><body>'.$wrappedtext.'</body></html>';
50 return $wrappedtext;
53 /**
54 * @param $m array
56 * @return string
58 function replaceEditSectionLinksCallback( $m ) {
59 $marker = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}" . Parser::MARKER_SUFFIX;
60 $this->mMarkerIndex++;
61 $this->mTokens->setPair( $marker, $m[0] );
62 return $marker;
65 /**
66 * @param $text string
67 * @return string
69 public function postprocess( $text ) {
70 return $this->mTokens->replace( $text );
75 /**
76 * Class to interact with HTML tidy
78 * Either the external tidy program or the in-process tidy extension
79 * will be used depending on availability. Override the default
80 * $wgTidyInternal setting to disable the internal if it's not working.
82 * @ingroup Parser
84 class MWTidy {
86 /**
87 * Interface with html tidy, used if $wgUseTidy = true.
88 * If tidy isn't able to correct the markup, the original will be
89 * returned in all its glory with a warning comment appended.
91 * @param $text String: hideous HTML input
92 * @return String: corrected HTML output
94 public static function tidy( $text ) {
95 global $wgTidyInternal;
97 $wrapper = new MWTidyWrapper;
98 $wrappedtext = $wrapper->getWrapped( $text );
100 if( $wgTidyInternal ) {
101 $correctedtext = self::execInternalTidy( $wrappedtext );
102 } else {
103 $correctedtext = self::execExternalTidy( $wrappedtext );
105 if( is_null( $correctedtext ) ) {
106 wfDebug( "Tidy error detected!\n" );
107 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
110 $correctedtext = $wrapper->postprocess( $correctedtext ); // restore any hidden tokens
112 return $correctedtext;
115 function replaceEditSectionLinksCallback( $m ) {
120 * Check HTML for errors, used if $wgValidateAllHtml = true.
122 * @param $text String
123 * @param &$errorStr String: return the error string
124 * @return Boolean: whether the HTML is valid
126 public static function checkErrors( $text, &$errorStr = null ) {
127 global $wgTidyInternal;
129 $retval = 0;
130 if( $wgTidyInternal ) {
131 $errorStr = self::execInternalTidy( $text, true, $retval );
132 } else {
133 $errorStr = self::execExternalTidy( $text, true, $retval );
135 return ( $retval < 0 && $errorStr == '' ) || $retval == 0;
139 * Spawn an external HTML tidy process and get corrected markup back from it.
140 * Also called in OutputHandler.php for full page validation
142 * @param $text String: HTML to check
143 * @param $stderr Boolean: Whether to read from STDERR rather than STDOUT
144 * @param &$retval Exit code (-1 on internal error)
145 * @return mixed String or null
147 private static function execExternalTidy( $text, $stderr = false, &$retval = null ) {
148 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
149 wfProfileIn( __METHOD__ );
151 $cleansource = '';
152 $opts = ' -utf8';
154 if( $stderr ) {
155 $descriptorspec = array(
156 0 => array( 'pipe', 'r' ),
157 1 => array( 'file', wfGetNull(), 'a' ),
158 2 => array( 'pipe', 'w' )
160 } else {
161 $descriptorspec = array(
162 0 => array( 'pipe', 'r' ),
163 1 => array( 'pipe', 'w' ),
164 2 => array( 'file', wfGetNull(), 'a' )
168 $readpipe = $stderr ? 2 : 1;
169 $pipes = array();
171 if( function_exists( 'proc_open' ) ) {
172 $process = proc_open( "$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes );
173 if ( is_resource( $process ) ) {
174 // Theoretically, this style of communication could cause a deadlock
175 // here. If the stdout buffer fills up, then writes to stdin could
176 // block. This doesn't appear to happen with tidy, because tidy only
177 // writes to stdout after it's finished reading from stdin. Search
178 // for tidyParseStdin and tidySaveStdout in console/tidy.c
179 fwrite( $pipes[0], $text );
180 fclose( $pipes[0] );
181 while ( !feof( $pipes[$readpipe] ) ) {
182 $cleansource .= fgets( $pipes[$readpipe], 1024 );
184 fclose( $pipes[$readpipe] );
185 $retval = proc_close( $process );
186 } else {
187 $retval = -1;
189 } else {
190 $retval = -1;
193 if( !$stderr && $cleansource == '' && $text != '' ) {
194 // Some kind of error happened, so we couldn't get the corrected text.
195 // Just give up; we'll use the source text and append a warning.
196 $cleansource = null;
198 wfProfileOut( __METHOD__ );
199 return $cleansource;
203 * Use the HTML tidy PECL extension to use the tidy library in-process,
204 * saving the overhead of spawning a new process.
206 * 'pear install tidy' should be able to compile the extension module.
208 * @param $text
209 * @param $stderr
210 * @param $retval
212 * @return string
214 private static function execInternalTidy( $text, $stderr = false, &$retval = null ) {
215 global $wgTidyConf, $wgDebugTidy;
216 wfProfileIn( __METHOD__ );
218 $tidy = new tidy;
219 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
221 if( $stderr ) {
222 $retval = $tidy->getStatus();
223 wfProfileOut( __METHOD__ );
224 return $tidy->errorBuffer;
225 } else {
226 $tidy->cleanRepair();
227 $retval = $tidy->getStatus();
228 if( $retval == 2 ) {
229 // 2 is magic number for fatal error
230 // http://www.php.net/manual/en/function.tidy-get-status.php
231 $cleansource = null;
232 } else {
233 $cleansource = tidy_get_output( $tidy );
235 if ( $wgDebugTidy && $retval > 0 ) {
236 $cleansource .= "<!--\nTidy reports:\n" .
237 str_replace( '-->', '--&gt;', $tidy->errorBuffer ) .
238 "\n-->";
241 wfProfileOut( __METHOD__ );
242 return $cleansource;