Support offsets in prefix searching
[mediawiki.git] / includes / parser / MWTidy.php
blobff62e9bd146621a1997404494bbe782e97bde763
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 string|null
169 private static function clean( $text, $stderr = false, &$retval = null ) {
170 global $wgTidyInternal;
172 if ( $wgTidyInternal ) {
173 if ( wfIsHHVM() ) {
174 if ( $stderr ) {
175 throw new MWException( __METHOD__.": error text return from HHVM tidy is not supported" );
177 return self::hhvmClean( $text, $retval );
178 } else {
179 return self::phpClean( $text, $stderr, $retval );
181 } else {
182 return self::externalClean( $text, $stderr, $retval );
187 * Spawn an external HTML tidy process and get corrected markup back from it.
188 * Also called in OutputHandler.php for full page validation
190 * @param string $text HTML to check
191 * @param bool $stderr Whether to read result from STDERR rather than STDOUT
192 * @param int &$retval Exit code (-1 on internal error)
193 * @return string|null
195 private static function externalClean( $text, $stderr = false, &$retval = null ) {
196 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
197 wfProfileIn( __METHOD__ );
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 wfProfileOut( __METHOD__ );
250 return $cleansource;
254 * Use the HTML tidy extension to use the tidy library in-process,
255 * saving the overhead of spawning a new process.
257 * @param string $text HTML to check
258 * @param bool $stderr Whether to read result from error status instead of output
259 * @param int &$retval Exit code (-1 on internal error)
260 * @return string|null
262 private static function phpClean( $text, $stderr = false, &$retval = null ) {
263 global $wgTidyConf, $wgDebugTidy;
264 wfProfileIn( __METHOD__ );
266 if ( !class_exists( 'tidy' ) ) {
267 wfWarn( "Unable to load internal tidy class." );
268 $retval = -1;
270 wfProfileOut( __METHOD__ );
271 return null;
274 $tidy = new tidy;
275 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
277 if ( $stderr ) {
278 $retval = $tidy->getStatus();
280 wfProfileOut( __METHOD__ );
281 return $tidy->errorBuffer;
284 $tidy->cleanRepair();
285 $retval = $tidy->getStatus();
286 if ( $retval == 2 ) {
287 // 2 is magic number for fatal error
288 // http://www.php.net/manual/en/function.tidy-get-status.php
289 $cleansource = null;
290 } else {
291 $cleansource = tidy_get_output( $tidy );
292 if ( $wgDebugTidy && $retval > 0 ) {
293 $cleansource .= "<!--\nTidy reports:\n" .
294 str_replace( '-->', '--&gt;', $tidy->errorBuffer ) .
295 "\n-->";
299 wfProfileOut( __METHOD__ );
300 return $cleansource;
304 * Use the tidy extension for HHVM from
305 * https://github.com/wikimedia/mediawiki-php-tidy
307 * This currently does not support the object-oriented interface, but
308 * tidy_repair_string() can be used for the most common tasks.
310 * @param string $text HTML to check
311 * @param int &$retval Exit code (-1 on internal error)
312 * @return string|null
314 private static function hhvmClean( $text, &$retval ) {
315 global $wgTidyConf;
316 wfProfileIn( __METHOD__ );
317 $cleansource = tidy_repair_string( $text, $wgTidyConf, 'utf8' );
318 if ( $cleansource === false ) {
319 $cleansource = null;
320 $retval = -1;
321 } else {
322 $retval = 0;
324 wfProfileOut( __METHOD__ );
325 return $cleansource;