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