Fix syntax terror from r79884
[lhc/web/wiklou.git] / includes / Math.php
1 <?php
2 /**
3 * Contain everything related to <math> </math> parsing
4 * @file
5 * @ingroup Parser
6 */
7
8 /**
9 * Takes LaTeX fragments, sends them to a helper program (texvc) for rendering
10 * to rasterized PNG and HTML and MathML approximations. An appropriate
11 * rendering form is picked and returned.
12 *
13 * @author Tomasz Wegrzanowski, with additions by Brion Vibber (2003, 2004)
14 * @ingroup Parser
15 */
16 class MathRenderer {
17 var $mode = MW_MATH_MODERN;
18 var $tex = '';
19 var $inputhash = '';
20 var $hash = '';
21 var $html = '';
22 var $mathml = '';
23 var $conservativeness = 0;
24
25 function __construct( $tex, $params=array() ) {
26 $this->tex = $tex;
27 $this->params = $params;
28 }
29
30 function setOutputMode( $mode ) {
31 $this->mode = $mode;
32 }
33
34 function render() {
35 global $wgTmpDirectory, $wgInputEncoding;
36 global $wgTexvc, $wgMathCheckFiles, $wgTexvcBackgroundColor;
37
38 if( $this->mode == MW_MATH_SOURCE ) {
39 # No need to render or parse anything more!
40 # New lines are replaced with spaces, which avoids confusing our parser (bugs 23190, 22818)
41 return ('<span class="tex">$ ' . str_replace( "\n", " ", htmlspecialchars( $this->tex ) ) . ' $</span>');
42 }
43 if( $this->tex == '' ) {
44 return; # bug 8372
45 }
46
47 if( !$this->_recall() ) {
48 if( $wgMathCheckFiles ) {
49 # Ensure that the temp and output directories are available before continuing...
50 if( !file_exists( $wgTmpDirectory ) ) {
51 if( !wfMkdirParents( $wgTmpDirectory ) ) {
52 return $this->_error( 'math_bad_tmpdir' );
53 }
54 } elseif( !is_dir( $wgTmpDirectory ) || !is_writable( $wgTmpDirectory ) ) {
55 return $this->_error( 'math_bad_tmpdir' );
56 }
57 }
58
59 if( !is_executable( $wgTexvc ) ) {
60 return $this->_error( 'math_notexvc' );
61 }
62 $cmd = $wgTexvc . ' ' .
63 escapeshellarg( $wgTmpDirectory ).' '.
64 escapeshellarg( $wgTmpDirectory ).' '.
65 escapeshellarg( $this->tex ).' '.
66 escapeshellarg( $wgInputEncoding ).' '.
67 escapeshellarg( $wgTexvcBackgroundColor );
68
69 if ( wfIsWindows() ) {
70 # Invoke it within cygwin sh, because texvc expects sh features in its default shell
71 $cmd = 'sh -c ' . wfEscapeShellArg( $cmd );
72 }
73
74 wfDebug( "TeX: $cmd\n" );
75 $contents = wfShellExec( $cmd );
76 wfDebug( "TeX output:\n $contents\n---\n" );
77
78 if (strlen($contents) == 0) {
79 return $this->_error( 'math_unknown_error' );
80 }
81
82 $retval = substr ($contents, 0, 1);
83 $errmsg = '';
84 if (($retval == 'C') || ($retval == 'M') || ($retval == 'L')) {
85 if ($retval == 'C') {
86 $this->conservativeness = 2;
87 } else if ($retval == 'M') {
88 $this->conservativeness = 1;
89 } else {
90 $this->conservativeness = 0;
91 }
92 $outdata = substr ($contents, 33);
93
94 $i = strpos($outdata, "\000");
95
96 $this->html = substr($outdata, 0, $i);
97 $this->mathml = substr($outdata, $i+1);
98 } else if (($retval == 'c') || ($retval == 'm') || ($retval == 'l')) {
99 $this->html = substr ($contents, 33);
100 if ($retval == 'c') {
101 $this->conservativeness = 2;
102 } else if ($retval == 'm') {
103 $this->conservativeness = 1;
104 } else {
105 $this->conservativeness = 0;
106 }
107 $this->mathml = null;
108 } else if ($retval == 'X') {
109 $this->html = null;
110 $this->mathml = substr ($contents, 33);
111 $this->conservativeness = 0;
112 } else if ($retval == '+') {
113 $this->html = null;
114 $this->mathml = null;
115 $this->conservativeness = 0;
116 } else {
117 $errbit = htmlspecialchars( substr($contents, 1) );
118 switch( $retval ) {
119 case 'E':
120 $errmsg = $this->_error( 'math_lexing_error', $errbit );
121 break;
122 case 'S':
123 $errmsg = $this->_error( 'math_syntax_error', $errbit );
124 break;
125 case 'F':
126 $errmsg = $this->_error( 'math_unknown_function', $errbit );
127 break;
128 default:
129 $errmsg = $this->_error( 'math_unknown_error', $errbit );
130 }
131 }
132
133 if ( !$errmsg ) {
134 $this->hash = substr ($contents, 1, 32);
135 }
136
137 wfRunHooks( 'MathAfterTexvc', array( &$this, &$errmsg ) );
138
139 if ( $errmsg ) {
140 return $errmsg;
141 }
142
143 if (!preg_match("/^[a-f0-9]{32}$/", $this->hash)) {
144 return $this->_error( 'math_unknown_error' );
145 }
146
147 if( !file_exists( "$wgTmpDirectory/{$this->hash}.png" ) ) {
148 return $this->_error( 'math_image_error' );
149 }
150
151 if( filesize( "$wgTmpDirectory/{$this->hash}.png" ) == 0 ) {
152 return $this->_error( 'math_image_error' );
153 }
154
155 $hashpath = $this->_getHashPath();
156 if( !file_exists( $hashpath ) ) {
157 wfSuppressWarnings();
158 $ret = wfMkdirParents( $hashpath, 0755 );
159 wfRestoreWarnings();
160 if( !$ret ) {
161 return $this->_error( 'math_bad_output' );
162 }
163 } elseif( !is_dir( $hashpath ) || !is_writable( $hashpath ) ) {
164 return $this->_error( 'math_bad_output' );
165 }
166
167 if( !rename( "$wgTmpDirectory/{$this->hash}.png", "$hashpath/{$this->hash}.png" ) ) {
168 return $this->_error( 'math_output_error' );
169 }
170
171 # Now save it back to the DB:
172 if ( !wfReadOnly() ) {
173 $outmd5_sql = pack('H32', $this->hash);
174
175 $md5_sql = pack('H32', $this->md5); # Binary packed, not hex
176
177 $dbw = wfGetDB( DB_MASTER );
178 $dbw->replace( 'math', array( 'math_inputhash' ),
179 array(
180 'math_inputhash' => $dbw->encodeBlob($md5_sql),
181 'math_outputhash' => $dbw->encodeBlob($outmd5_sql),
182 'math_html_conservativeness' => $this->conservativeness,
183 'math_html' => $this->html,
184 'math_mathml' => $this->mathml,
185 ), __METHOD__
186 );
187 }
188
189 // If we're replacing an older version of the image, make sure it's current.
190 global $wgUseSquid;
191 if ( $wgUseSquid ) {
192 $urls = array( $this->_mathImageUrl() );
193 $u = new SquidUpdate( $urls );
194 $u->doUpdate();
195 }
196 }
197
198 return $this->_doRender();
199 }
200
201 function _error( $msg, $append = '' ) {
202 $mf = htmlspecialchars( wfMsg( 'math_failure' ) );
203 $errmsg = htmlspecialchars( wfMsg( $msg ) );
204 $source = htmlspecialchars( str_replace( "\n", ' ', $this->tex ) );
205 return "<strong class='error'>$mf ($errmsg$append): $source</strong>\n";
206 }
207
208 function _recall() {
209 global $wgMathDirectory, $wgMathCheckFiles;
210
211 $this->md5 = md5( $this->tex );
212 $dbr = wfGetDB( DB_SLAVE );
213 $rpage = $dbr->selectRow( 'math',
214 array( 'math_outputhash','math_html_conservativeness','math_html','math_mathml' ),
215 array( 'math_inputhash' => $dbr->encodeBlob(pack("H32", $this->md5))), # Binary packed, not hex
216 __METHOD__
217 );
218
219 if( $rpage !== false ) {
220 # Tailing 0x20s can get dropped by the database, add it back on if necessary:
221 $xhash = unpack( 'H32md5', $dbr->decodeBlob($rpage->math_outputhash) . " " );
222 $this->hash = $xhash ['md5'];
223
224 $this->conservativeness = $rpage->math_html_conservativeness;
225 $this->html = $rpage->math_html;
226 $this->mathml = $rpage->math_mathml;
227
228 $filename = $this->_getHashPath() . "/{$this->hash}.png";
229
230 if( !$wgMathCheckFiles ) {
231 // Short-circuit the file existence & migration checks
232 return true;
233 }
234
235 if( file_exists( $filename ) ) {
236 if( filesize( $filename ) == 0 ) {
237 // Some horrible error corrupted stuff :(
238 wfSuppressWarnings();
239 unlink( $filename );
240 wfRestoreWarnings();
241 } else {
242 return true;
243 }
244 }
245
246 if( file_exists( $wgMathDirectory . "/{$this->hash}.png" ) ) {
247 $hashpath = $this->_getHashPath();
248
249 if( !file_exists( $hashpath ) ) {
250 wfSuppressWarnings();
251 $ret = wfMkdirParents( $hashpath, 0755 );
252 wfRestoreWarnings();
253 if( !$ret ) {
254 return false;
255 }
256 } elseif( !is_dir( $hashpath ) || !is_writable( $hashpath ) ) {
257 return false;
258 }
259 if ( function_exists( "link" ) ) {
260 return link ( $wgMathDirectory . "/{$this->hash}.png",
261 $hashpath . "/{$this->hash}.png" );
262 } else {
263 return rename ( $wgMathDirectory . "/{$this->hash}.png",
264 $hashpath . "/{$this->hash}.png" );
265 }
266 }
267
268 }
269
270 # Missing from the database and/or the render cache
271 return false;
272 }
273
274 /**
275 * Select among PNG, HTML, or MathML output depending on
276 */
277 function _doRender() {
278 if( $this->mode == MW_MATH_MATHML && $this->mathml != '' ) {
279 return Xml::tags( 'math',
280 $this->_attribs( 'math',
281 array( 'xmlns' => 'http://www.w3.org/1998/Math/MathML' ) ),
282 $this->mathml );
283 }
284 if (($this->mode == MW_MATH_PNG) || ($this->html == '') ||
285 (($this->mode == MW_MATH_SIMPLE) && ($this->conservativeness != 2)) ||
286 (($this->mode == MW_MATH_MODERN || $this->mode == MW_MATH_MATHML) && ($this->conservativeness == 0))) {
287 return $this->_linkToMathImage();
288 } else {
289 return Xml::tags( 'span',
290 $this->_attribs( 'span',
291 array( 'class' => 'texhtml' ) ),
292 $this->html );
293 }
294 }
295
296 function _attribs( $tag, $defaults=array(), $overrides=array() ) {
297 $attribs = Sanitizer::validateTagAttributes( $this->params, $tag );
298 $attribs = Sanitizer::mergeAttributes( $defaults, $attribs );
299 $attribs = Sanitizer::mergeAttributes( $attribs, $overrides );
300 return $attribs;
301 }
302
303 function _linkToMathImage() {
304 $url = $this->_mathImageUrl();
305
306 return Xml::element( 'img',
307 $this->_attribs(
308 'img',
309 array(
310 'class' => 'tex',
311 'alt' => $this->tex ),
312 array(
313 'src' => $url ) ) );
314 }
315
316 function _mathImageUrl() {
317 global $wgMathPath;
318 $dir = $this->_getHashSubPath();
319 return "$wgMathPath/$dir/{$this->hash}.png";
320 }
321
322 function _getHashPath() {
323 global $wgMathDirectory;
324 $path = $wgMathDirectory .'/' . $this->_getHashSubPath();
325 wfDebug( "TeX: getHashPath, hash is: $this->hash, path is: $path\n" );
326 return $path;
327 }
328
329 function _getHashSubPath() {
330 return substr($this->hash, 0, 1)
331 .'/'. substr($this->hash, 1, 1)
332 .'/'. substr($this->hash, 2, 1);
333 }
334
335 public static function renderMath( $tex, $params=array(), ParserOptions $parserOptions = null ) {
336 $math = new MathRenderer( $tex, $params );
337 if ( $parserOptions )
338 $math->setOutputMode( $parserOptions->getMath() );
339 return $math->render();
340 }
341 }