Merge "(bug 37755) Set robot meta tags for 'view source' pages"
[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, 'replaceEditSectionLinksCallback' ), $text );
65
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 );
69
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>';
74
75 return $wrappedtext;
76 }
77
78 /**
79 * @param $m array
80 *
81 * @return string
82 */
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;
88 }
89
90 /**
91 * @param $text string
92 * @return string
93 */
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 );
97
98 // Restore the contents of placeholder tokens
99 $text = $this->mTokens->replace( $text );
100
101 return $text;
102 }
103
104 }
105
106 /**
107 * Class to interact with HTML tidy
108 *
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.
112 *
113 * @ingroup Parser
114 */
115 class MWTidy {
116 /**
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.
120 *
121 * @param $text String: hideous HTML input
122 * @return String: corrected HTML output
123 */
124 public static function tidy( $text ) {
125 global $wgTidyInternal;
126
127 $wrapper = new MWTidyWrapper;
128 $wrappedtext = $wrapper->getWrapped( $text );
129
130 $retVal = null;
131 if ( $wgTidyInternal ) {
132 $correctedtext = self::execInternalTidy( $wrappedtext, false, $retVal );
133 } else {
134 $correctedtext = self::execExternalTidy( $wrappedtext, false, $retVal );
135 }
136
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";
143 }
144
145 $correctedtext = $wrapper->postprocess( $correctedtext ); // restore any hidden tokens
146
147 return $correctedtext;
148 }
149
150 /**
151 * Check HTML for errors, used if $wgValidateAllHtml = true.
152 *
153 * @param $text String
154 * @param &$errorStr String: return the error string
155 * @return Boolean: whether the HTML is valid
156 */
157 public static function checkErrors( $text, &$errorStr = null ) {
158 global $wgTidyInternal;
159
160 $retval = 0;
161 if( $wgTidyInternal ) {
162 $errorStr = self::execInternalTidy( $text, true, $retval );
163 } else {
164 $errorStr = self::execExternalTidy( $text, true, $retval );
165 }
166
167 return ( $retval < 0 && $errorStr == '' ) || $retval == 0;
168 }
169
170 /**
171 * Spawn an external HTML tidy process and get corrected markup back from it.
172 * Also called in OutputHandler.php for full page validation
173 *
174 * @param $text String: 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
178 */
179 private static function execExternalTidy( $text, $stderr = false, &$retval = null ) {
180 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
181 wfProfileIn( __METHOD__ );
182
183 $cleansource = '';
184 $opts = ' -utf8';
185
186 if ( $stderr ) {
187 $descriptorspec = array(
188 0 => array( 'pipe', 'r' ),
189 1 => array( 'file', wfGetNull(), 'a' ),
190 2 => array( 'pipe', 'w' )
191 );
192 } else {
193 $descriptorspec = array(
194 0 => array( 'pipe', 'r' ),
195 1 => array( 'pipe', 'w' ),
196 2 => array( 'file', wfGetNull(), 'a' )
197 );
198 }
199
200 $readpipe = $stderr ? 2 : 1;
201 $pipes = array();
202
203 $process = proc_open(
204 "$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes );
205
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 );
216 }
217 fclose( $pipes[$readpipe] );
218 $retval = proc_close( $process );
219 } else {
220 wfWarn( "Unable to start external tidy process" );
221 $retval = -1;
222 }
223
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;
228 }
229
230 wfProfileOut( __METHOD__ );
231 return $cleansource;
232 }
233
234 /**
235 * Use the HTML tidy extension to use the tidy library in-process,
236 * saving the overhead of spawning a new process.
237 *
238 * @param $text String: 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
242 */
243 private static function execInternalTidy( $text, $stderr = false, &$retval = null ) {
244 global $wgTidyConf, $wgDebugTidy;
245 wfProfileIn( __METHOD__ );
246
247 if ( !MWInit::classExists( 'tidy' ) ) {
248 wfWarn( "Unable to load internal tidy class." );
249 $retval = -1;
250
251 wfProfileOut( __METHOD__ );
252 return null;
253 }
254
255 $tidy = new tidy;
256 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
257
258 if ( $stderr ) {
259 $retval = $tidy->getStatus();
260
261 wfProfileOut( __METHOD__ );
262 return $tidy->errorBuffer;
263 } else {
264 $tidy->cleanRepair();
265 $retval = $tidy->getStatus();
266 if ( $retval == 2 ) {
267 // 2 is magic number for fatal error
268 // http://www.php.net/manual/en/function.tidy-get-status.php
269 $cleansource = null;
270 } else {
271 $cleansource = tidy_get_output( $tidy );
272 if ( $wgDebugTidy && $retval > 0 ) {
273 $cleansource .= "<!--\nTidy reports:\n" .
274 str_replace( '-->', '--&gt;', $tidy->errorBuffer ) .
275 "\n-->";
276 }
277 }
278
279 wfProfileOut( __METHOD__ );
280 return $cleansource;
281 }
282 }
283 }