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