Fixing some of the "@return true" or "@return false", need to be "@return bool" and...
[lhc/web/wiklou.git] / includes / parser / Tidy.php
1 <?php
2 /**
3 * HTML validation and correction
4 *
5 * @file
6 */
7
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
14 *
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.
17 */
18 class MWTidyWrapper {
19
20 /**
21 * @var ReplacementArray
22 */
23 protected $mTokens;
24
25 protected $mUniqPrefix;
26
27 protected $mMarkerIndex;
28
29 public function __construct() {
30 $this->mTokens = null;
31 $this->mUniqPrefix = null;
32 }
33
34 /**
35 * @param $text string
36 * @return string
37 */
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
44 $wrappedtext = preg_replace_callback( ParserOutput::EDITSECTION_REGEX,
45 array( &$this, 'replaceEditSectionLinksCallback' ), $text );
46
47 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
48 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
49 '<head><title>test</title></head><body>'.$wrappedtext.'</body></html>';
50
51 return $wrappedtext;
52 }
53
54 /**
55 * @param $m array
56 *
57 * @return string
58 */
59 function replaceEditSectionLinksCallback( $m ) {
60 $marker = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}" . Parser::MARKER_SUFFIX;
61 $this->mMarkerIndex++;
62 $this->mTokens->setPair( $marker, $m[0] );
63 return $marker;
64 }
65
66 /**
67 * @param $text string
68 * @return string
69 */
70 public function postprocess( $text ) {
71 return $this->mTokens->replace( $text );
72 }
73
74 }
75
76 /**
77 * Class to interact with HTML tidy
78 *
79 * Either the external tidy program or the in-process tidy extension
80 * will be used depending on availability. Override the default
81 * $wgTidyInternal setting to disable the internal if it's not working.
82 *
83 * @ingroup Parser
84 */
85 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.
90 *
91 * @param $text String: hideous HTML input
92 * @return String: corrected HTML output
93 */
94 public static function tidy( $text ) {
95 global $wgTidyInternal;
96
97 $wrapper = new MWTidyWrapper;
98 $wrappedtext = $wrapper->getWrapped( $text );
99
100 $retVal = null;
101 if ( $wgTidyInternal ) {
102 $correctedtext = self::execInternalTidy( $wrappedtext, false, $retVal );
103 } else {
104 $correctedtext = self::execExternalTidy( $wrappedtext, false, $retVal );
105 }
106
107 if ( $retVal < 0 ) {
108 wfDebug( "Possible tidy configuration error!\n" );
109 return $text . "\n<!-- Tidy was unable to run -->\n";
110 } elseif ( is_null( $correctedtext ) ) {
111 wfDebug( "Tidy error detected!\n" );
112 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
113 }
114
115 $correctedtext = $wrapper->postprocess( $correctedtext ); // restore any hidden tokens
116
117 return $correctedtext;
118 }
119
120 /**
121 * Check HTML for errors, used if $wgValidateAllHtml = true.
122 *
123 * @param $text String
124 * @param &$errorStr String: return the error string
125 * @return Boolean: whether the HTML is valid
126 */
127 public static function checkErrors( $text, &$errorStr = null ) {
128 global $wgTidyInternal;
129
130 $retval = 0;
131 if( $wgTidyInternal ) {
132 $errorStr = self::execInternalTidy( $text, true, $retval );
133 } else {
134 $errorStr = self::execExternalTidy( $text, true, $retval );
135 }
136
137 return ( $retval < 0 && $errorStr == '' ) || $retval == 0;
138 }
139
140 /**
141 * Spawn an external HTML tidy process and get corrected markup back from it.
142 * Also called in OutputHandler.php for full page validation
143 *
144 * @param $text String: HTML to check
145 * @param $stderr Boolean: Whether to read result from STDERR rather than STDOUT
146 * @param &$retval int Exit code (-1 on internal error)
147 * @return mixed String or null
148 */
149 private static function execExternalTidy( $text, $stderr = false, &$retval = null ) {
150 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
151 wfProfileIn( __METHOD__ );
152
153 $cleansource = '';
154 $opts = ' -utf8';
155
156 if ( $stderr ) {
157 $descriptorspec = array(
158 0 => array( 'pipe', 'r' ),
159 1 => array( 'file', wfGetNull(), 'a' ),
160 2 => array( 'pipe', 'w' )
161 );
162 } else {
163 $descriptorspec = array(
164 0 => array( 'pipe', 'r' ),
165 1 => array( 'pipe', 'w' ),
166 2 => array( 'file', wfGetNull(), 'a' )
167 );
168 }
169
170 $readpipe = $stderr ? 2 : 1;
171 $pipes = array();
172
173 $process = proc_open(
174 "$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes );
175
176 if ( is_resource( $process ) ) {
177 // Theoretically, this style of communication could cause a deadlock
178 // here. If the stdout buffer fills up, then writes to stdin could
179 // block. This doesn't appear to happen with tidy, because tidy only
180 // writes to stdout after it's finished reading from stdin. Search
181 // for tidyParseStdin and tidySaveStdout in console/tidy.c
182 fwrite( $pipes[0], $text );
183 fclose( $pipes[0] );
184 while ( !feof( $pipes[$readpipe] ) ) {
185 $cleansource .= fgets( $pipes[$readpipe], 1024 );
186 }
187 fclose( $pipes[$readpipe] );
188 $retval = proc_close( $process );
189 } else {
190 wfWarn( "Unable to start external tidy process" );
191 $retval = -1;
192 }
193
194 if ( !$stderr && $cleansource == '' && $text != '' ) {
195 // Some kind of error happened, so we couldn't get the corrected text.
196 // Just give up; we'll use the source text and append a warning.
197 $cleansource = null;
198 }
199
200 wfProfileOut( __METHOD__ );
201 return $cleansource;
202 }
203
204 /**
205 * Use the HTML tidy extension to use the tidy library in-process,
206 * saving the overhead of spawning a new process.
207 *
208 * @param $text String: HTML to check
209 * @param $stderr Boolean: Whether to read result from error status instead of output
210 * @param &$retval int Exit code (-1 on internal error)
211 * @return mixed String or null
212 */
213 private static function execInternalTidy( $text, $stderr = false, &$retval = null ) {
214 global $wgTidyConf, $wgDebugTidy;
215 wfProfileIn( __METHOD__ );
216
217 if ( !MWInit::classExists( 'tidy' ) ) {
218 wfWarn( "Unable to load internal tidy class." );
219 $retval = -1;
220
221 wfProfileOut( __METHOD__ );
222 return null;
223 }
224
225 $tidy = new tidy;
226 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
227
228 if ( $stderr ) {
229 $retval = $tidy->getStatus();
230
231 wfProfileOut( __METHOD__ );
232 return $tidy->errorBuffer;
233 } else {
234 $tidy->cleanRepair();
235 $retval = $tidy->getStatus();
236 if ( $retval == 2 ) {
237 // 2 is magic number for fatal error
238 // http://www.php.net/manual/en/function.tidy-get-status.php
239 $cleansource = null;
240 } else {
241 $cleansource = tidy_get_output( $tidy );
242 if ( $wgDebugTidy && $retval > 0 ) {
243 $cleansource .= "<!--\nTidy reports:\n" .
244 str_replace( '-->', '--&gt;', $tidy->errorBuffer ) .
245 "\n-->";
246 }
247 }
248
249 wfProfileOut( __METHOD__ );
250 return $cleansource;
251 }
252 }
253 }