removed ts_tags from getQueryInfo. it's already added in ChangeTags::modifyDisplayQue...
[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;
37 $fname = 'MathRenderer::render';
38
39 if( $this->mode == MW_MATH_SOURCE ) {
40 # No need to render or parse anything more!
41 return ('$ '.htmlspecialchars( $this->tex ).' $');
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( function_exists( 'is_executable' ) && !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
68 if ( wfIsWindows() ) {
69 # Invoke it within cygwin sh, because texvc expects sh features in its default shell
70 $cmd = 'sh -c ' . wfEscapeShellArg( $cmd );
71 }
72
73 wfDebug( "TeX: $cmd\n" );
74 $contents = `$cmd`;
75 wfDebug( "TeX output:\n $contents\n---\n" );
76
77 if (strlen($contents) == 0) {
78 return $this->_error( 'math_unknown_error' );
79 }
80
81 $retval = substr ($contents, 0, 1);
82 $errmsg = '';
83 if (($retval == 'C') || ($retval == 'M') || ($retval == 'L')) {
84 if ($retval == 'C') {
85 $this->conservativeness = 2;
86 } else if ($retval == 'M') {
87 $this->conservativeness = 1;
88 } else {
89 $this->conservativeness = 0;
90 }
91 $outdata = substr ($contents, 33);
92
93 $i = strpos($outdata, "\000");
94
95 $this->html = substr($outdata, 0, $i);
96 $this->mathml = substr($outdata, $i+1);
97 } else if (($retval == 'c') || ($retval == 'm') || ($retval == 'l')) {
98 $this->html = substr ($contents, 33);
99 if ($retval == 'c') {
100 $this->conservativeness = 2;
101 } else if ($retval == 'm') {
102 $this->conservativeness = 1;
103 } else {
104 $this->conservativeness = 0;
105 }
106 $this->mathml = NULL;
107 } else if ($retval == 'X') {
108 $this->html = NULL;
109 $this->mathml = substr ($contents, 33);
110 $this->conservativeness = 0;
111 } else if ($retval == '+') {
112 $this->html = NULL;
113 $this->mathml = NULL;
114 $this->conservativeness = 0;
115 } else {
116 $errbit = htmlspecialchars( substr($contents, 1) );
117 switch( $retval ) {
118 case 'E':
119 $errmsg = $this->_error( 'math_lexing_error', $errbit );
120 break;
121 case 'S':
122 $errmsg = $this->_error( 'math_syntax_error', $errbit );
123 break;
124 case 'F':
125 $errmsg = $this->_error( 'math_unknown_function', $errbit );
126 break;
127 default:
128 $errmsg = $this->_error( 'math_unknown_error', $errbit );
129 }
130 }
131
132 if ( !$errmsg ) {
133 $this->hash = substr ($contents, 1, 32);
134 }
135
136 wfRunHooks( 'MathAfterTexvc', array( &$this, &$errmsg ) );
137
138 if ( $errmsg ) {
139 return $errmsg;
140 }
141
142 if (!preg_match("/^[a-f0-9]{32}$/", $this->hash)) {
143 return $this->_error( 'math_unknown_error' );
144 }
145
146 if( !file_exists( "$wgTmpDirectory/{$this->hash}.png" ) ) {
147 return $this->_error( 'math_image_error' );
148 }
149
150 if( filesize( "$wgTmpDirectory/{$this->hash}.png" ) == 0 ) {
151 return $this->_error( 'math_image_error' );
152 }
153
154 $hashpath = $this->_getHashPath();
155 if( !file_exists( $hashpath ) ) {
156 if( !@wfMkdirParents( $hashpath, 0755 ) ) {
157 return $this->_error( 'math_bad_output' );
158 }
159 } elseif( !is_dir( $hashpath ) || !is_writable( $hashpath ) ) {
160 return $this->_error( 'math_bad_output' );
161 }
162
163 if( !rename( "$wgTmpDirectory/{$this->hash}.png", "$hashpath/{$this->hash}.png" ) ) {
164 return $this->_error( 'math_output_error' );
165 }
166
167 # Now save it back to the DB:
168 if ( !wfReadOnly() ) {
169 $outmd5_sql = pack('H32', $this->hash);
170
171 $md5_sql = pack('H32', $this->md5); # Binary packed, not hex
172
173 $dbw = wfGetDB( DB_MASTER );
174 $dbw->replace( 'math', array( 'math_inputhash' ),
175 array(
176 'math_inputhash' => $dbw->encodeBlob($md5_sql),
177 'math_outputhash' => $dbw->encodeBlob($outmd5_sql),
178 'math_html_conservativeness' => $this->conservativeness,
179 'math_html' => $this->html,
180 'math_mathml' => $this->mathml,
181 ), $fname
182 );
183 }
184
185 // If we're replacing an older version of the image, make sure it's current.
186 global $wgUseSquid;
187 if ( $wgUseSquid ) {
188 $urls = array( $this->_mathImageUrl() );
189 $u = new SquidUpdate( $urls );
190 $u->doUpdate();
191 }
192 }
193
194 return $this->_doRender();
195 }
196
197 function _error( $msg, $append = '' ) {
198 $mf = htmlspecialchars( wfMsg( 'math_failure' ) );
199 $errmsg = htmlspecialchars( wfMsg( $msg ) );
200 $source = htmlspecialchars( str_replace( "\n", ' ', $this->tex ) );
201 return "<strong class='error'>$mf ($errmsg$append): $source</strong>\n";
202 }
203
204 function _recall() {
205 global $wgMathDirectory, $wgMathCheckFiles;
206 $fname = 'MathRenderer::_recall';
207
208 $this->md5 = md5( $this->tex );
209 $dbr = wfGetDB( DB_SLAVE );
210 $rpage = $dbr->selectRow( 'math',
211 array( 'math_outputhash','math_html_conservativeness','math_html','math_mathml' ),
212 array( 'math_inputhash' => $dbr->encodeBlob(pack("H32", $this->md5))), # Binary packed, not hex
213 $fname
214 );
215
216 if( $rpage !== false ) {
217 # Tailing 0x20s can get dropped by the database, add it back on if necessary:
218 $xhash = unpack( 'H32md5', $dbr->decodeBlob($rpage->math_outputhash) . " " );
219 $this->hash = $xhash ['md5'];
220
221 $this->conservativeness = $rpage->math_html_conservativeness;
222 $this->html = $rpage->math_html;
223 $this->mathml = $rpage->math_mathml;
224
225 $filename = $this->_getHashPath() . "/{$this->hash}.png";
226
227 if( !$wgMathCheckFiles ) {
228 // Short-circuit the file existence & migration checks
229 return true;
230 }
231
232 if( file_exists( $filename ) ) {
233 if( filesize( $filename ) == 0 ) {
234 // Some horrible error corrupted stuff :(
235 @unlink( $filename );
236 } else {
237 return true;
238 }
239 }
240
241 if( file_exists( $wgMathDirectory . "/{$this->hash}.png" ) ) {
242 $hashpath = $this->_getHashPath();
243
244 if( !file_exists( $hashpath ) ) {
245 if( !@wfMkdirParents( $hashpath, 0755 ) ) {
246 return false;
247 }
248 } elseif( !is_dir( $hashpath ) || !is_writable( $hashpath ) ) {
249 return false;
250 }
251 if ( function_exists( "link" ) ) {
252 return link ( $wgMathDirectory . "/{$this->hash}.png",
253 $hashpath . "/{$this->hash}.png" );
254 } else {
255 return rename ( $wgMathDirectory . "/{$this->hash}.png",
256 $hashpath . "/{$this->hash}.png" );
257 }
258 }
259
260 }
261
262 # Missing from the database and/or the render cache
263 return false;
264 }
265
266 /**
267 * Select among PNG, HTML, or MathML output depending on
268 */
269 function _doRender() {
270 if( $this->mode == MW_MATH_MATHML && $this->mathml != '' ) {
271 return Xml::tags( 'math',
272 $this->_attribs( 'math',
273 array( 'xmlns' => 'http://www.w3.org/1998/Math/MathML' ) ),
274 $this->mathml );
275 }
276 if (($this->mode == MW_MATH_PNG) || ($this->html == '') ||
277 (($this->mode == MW_MATH_SIMPLE) && ($this->conservativeness != 2)) ||
278 (($this->mode == MW_MATH_MODERN || $this->mode == MW_MATH_MATHML) && ($this->conservativeness == 0))) {
279 return $this->_linkToMathImage();
280 } else {
281 return Xml::tags( 'span',
282 $this->_attribs( 'span',
283 array( 'class' => 'texhtml' ) ),
284 $this->html );
285 }
286 }
287
288 function _attribs( $tag, $defaults=array(), $overrides=array() ) {
289 $attribs = Sanitizer::validateTagAttributes( $this->params, $tag );
290 $attribs = Sanitizer::mergeAttributes( $defaults, $attribs );
291 $attribs = Sanitizer::mergeAttributes( $attribs, $overrides );
292 return $attribs;
293 }
294
295 function _linkToMathImage() {
296 $url = $this->_mathImageUrl();
297
298 return Xml::element( 'img',
299 $this->_attribs(
300 'img',
301 array(
302 'class' => 'tex',
303 'alt' => $this->tex ),
304 array(
305 'src' => $url ) ) );
306 }
307
308 function _mathImageUrl() {
309 global $wgMathPath;
310 $dir = $this->_getHashSubPath();
311 return "$wgMathPath/$dir/{$this->hash}.png";
312 }
313
314 function _getHashPath() {
315 global $wgMathDirectory;
316 $path = $wgMathDirectory .'/' . $this->_getHashSubPath();
317 wfDebug( "TeX: getHashPath, hash is: $this->hash, path is: $path\n" );
318 return $path;
319 }
320
321 function _getHashSubPath() {
322 return substr($this->hash, 0, 1)
323 .'/'. substr($this->hash, 1, 1)
324 .'/'. substr($this->hash, 2, 1);
325 }
326
327 public static function renderMath( $tex, $params=array() ) {
328 global $wgUser;
329 $math = new MathRenderer( $tex, $params );
330 $math->setOutputMode( $wgUser->getOption('math'));
331 return $math->render();
332 }
333 }