Merge "Add url parameter to trigger autogenerated gallery type."
[mediawiki.git] / includes / parser / Tidy.php
blob06251402ddaac21b28fe6616e62a84f3e7a47c8c
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 $text string
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, 'replaceEditSectionLinksCallback' ), $text );
66 // Modify inline Microdata <link> and <meta> elements so they say <html-link> and <html-meta> so
67 // we can trick Tidy into not stripping them out by including them in tidy's new-empty-tags config
68 $wrappedtext = preg_replace( '!<(link|meta)([^>]*?)(/{0,1}>)!', '<html-$1$2$3', $wrappedtext );
70 // Wrap the whole thing in a doctype and body for Tidy.
71 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' .
72 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>' .
73 '<head><title>test</title></head><body>' . $wrappedtext . '</body></html>';
75 return $wrappedtext;
78 /**
79 * @param $m array
81 * @return string
83 function replaceEditSectionLinksCallback( $m ) {
84 $marker = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}" . Parser::MARKER_SUFFIX;
85 $this->mMarkerIndex++;
86 $this->mTokens->setPair( $marker, $m[0] );
87 return $marker;
90 /**
91 * @param $text string
92 * @return string
94 public function postprocess( $text ) {
95 // Revert <html-{link,meta}> back to <{link,meta}>
96 $text = preg_replace( '!<html-(link|meta)([^>]*?)(/{0,1}>)!', '<$1$2$3', $text );
98 // Restore the contents of placeholder tokens
99 $text = $this->mTokens->replace( $text );
101 return $text;
107 * Class to interact with HTML tidy
109 * Either the external tidy program or the in-process tidy extension
110 * will be used depending on availability. Override the default
111 * $wgTidyInternal setting to disable the internal if it's not working.
113 * @ingroup Parser
115 class MWTidy {
117 * Interface with html tidy, used if $wgUseTidy = true.
118 * If tidy isn't able to correct the markup, the original will be
119 * returned in all its glory with a warning comment appended.
121 * @param string $text hideous HTML input
122 * @return String: corrected HTML output
124 public static function tidy( $text ) {
125 global $wgTidyInternal;
127 $wrapper = new MWTidyWrapper;
128 $wrappedtext = $wrapper->getWrapped( $text );
130 $retVal = null;
131 if ( $wgTidyInternal ) {
132 $correctedtext = self::execInternalTidy( $wrappedtext, false, $retVal );
133 } else {
134 $correctedtext = self::execExternalTidy( $wrappedtext, false, $retVal );
137 if ( $retVal < 0 ) {
138 wfDebug( "Possible tidy configuration error!\n" );
139 return $text . "\n<!-- Tidy was unable to run -->\n";
140 } elseif ( is_null( $correctedtext ) ) {
141 wfDebug( "Tidy error detected!\n" );
142 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
145 $correctedtext = $wrapper->postprocess( $correctedtext ); // restore any hidden tokens
147 return $correctedtext;
151 * Check HTML for errors, used if $wgValidateAllHtml = true.
153 * @param $text String
154 * @param &$errorStr String: return the error string
155 * @return Boolean: whether the HTML is valid
157 public static function checkErrors( $text, &$errorStr = null ) {
158 global $wgTidyInternal;
160 $retval = 0;
161 if ( $wgTidyInternal ) {
162 $errorStr = self::execInternalTidy( $text, true, $retval );
163 } else {
164 $errorStr = self::execExternalTidy( $text, true, $retval );
167 return ( $retval < 0 && $errorStr == '' ) || $retval == 0;
171 * Spawn an external HTML tidy process and get corrected markup back from it.
172 * Also called in OutputHandler.php for full page validation
174 * @param string $text HTML to check
175 * @param $stderr Boolean: Whether to read result from STDERR rather than STDOUT
176 * @param &$retval int Exit code (-1 on internal error)
177 * @return mixed String or null
179 private static function execExternalTidy( $text, $stderr = false, &$retval = null ) {
180 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
181 wfProfileIn( __METHOD__ );
183 $cleansource = '';
184 $opts = ' -utf8';
186 if ( $stderr ) {
187 $descriptorspec = array(
188 0 => array( 'pipe', 'r' ),
189 1 => array( 'file', wfGetNull(), 'a' ),
190 2 => array( 'pipe', 'w' )
192 } else {
193 $descriptorspec = array(
194 0 => array( 'pipe', 'r' ),
195 1 => array( 'pipe', 'w' ),
196 2 => array( 'file', wfGetNull(), 'a' )
200 $readpipe = $stderr ? 2 : 1;
201 $pipes = array();
203 $process = proc_open(
204 "$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes );
206 if ( is_resource( $process ) ) {
207 // Theoretically, this style of communication could cause a deadlock
208 // here. If the stdout buffer fills up, then writes to stdin could
209 // block. This doesn't appear to happen with tidy, because tidy only
210 // writes to stdout after it's finished reading from stdin. Search
211 // for tidyParseStdin and tidySaveStdout in console/tidy.c
212 fwrite( $pipes[0], $text );
213 fclose( $pipes[0] );
214 while ( !feof( $pipes[$readpipe] ) ) {
215 $cleansource .= fgets( $pipes[$readpipe], 1024 );
217 fclose( $pipes[$readpipe] );
218 $retval = proc_close( $process );
219 } else {
220 wfWarn( "Unable to start external tidy process" );
221 $retval = -1;
224 if ( !$stderr && $cleansource == '' && $text != '' ) {
225 // Some kind of error happened, so we couldn't get the corrected text.
226 // Just give up; we'll use the source text and append a warning.
227 $cleansource = null;
230 wfProfileOut( __METHOD__ );
231 return $cleansource;
235 * Use the HTML tidy extension to use the tidy library in-process,
236 * saving the overhead of spawning a new process.
238 * @param string $text HTML to check
239 * @param $stderr Boolean: Whether to read result from error status instead of output
240 * @param &$retval int Exit code (-1 on internal error)
241 * @return mixed String or null
243 private static function execInternalTidy( $text, $stderr = false, &$retval = null ) {
244 global $wgTidyConf, $wgDebugTidy;
245 wfProfileIn( __METHOD__ );
247 if ( !class_exists( 'tidy' ) ) {
248 wfWarn( "Unable to load internal tidy class." );
249 $retval = -1;
251 wfProfileOut( __METHOD__ );
252 return null;
255 $tidy = new tidy;
256 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
258 if ( $stderr ) {
259 $retval = $tidy->getStatus();
261 wfProfileOut( __METHOD__ );
262 return $tidy->errorBuffer;
265 $tidy->cleanRepair();
266 $retval = $tidy->getStatus();
267 if ( $retval == 2 ) {
268 // 2 is magic number for fatal error
269 // http://www.php.net/manual/en/function.tidy-get-status.php
270 $cleansource = null;
271 } else {
272 $cleansource = tidy_get_output( $tidy );
273 if ( $wgDebugTidy && $retval > 0 ) {
274 $cleansource .= "<!--\nTidy reports:\n" .
275 str_replace( '-->', '--&gt;', $tidy->errorBuffer ) .
276 "\n-->";
280 wfProfileOut( __METHOD__ );
281 return $cleansource;