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