Remove various unused parameters
[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 if( !@wfMkdirParents( $hashpath, 0755 ) ) {
158 return $this->_error( 'math_bad_output' );
159 }
160 } elseif( !is_dir( $hashpath ) || !is_writable( $hashpath ) ) {
161 return $this->_error( 'math_bad_output' );
162 }
163
164 if( !rename( "$wgTmpDirectory/{$this->hash}.png", "$hashpath/{$this->hash}.png" ) ) {
165 return $this->_error( 'math_output_error' );
166 }
167
168 # Now save it back to the DB:
169 if ( !wfReadOnly() ) {
170 $outmd5_sql = pack('H32', $this->hash);
171
172 $md5_sql = pack('H32', $this->md5); # Binary packed, not hex
173
174 $dbw = wfGetDB( DB_MASTER );
175 $dbw->replace( 'math', array( 'math_inputhash' ),
176 array(
177 'math_inputhash' => $dbw->encodeBlob($md5_sql),
178 'math_outputhash' => $dbw->encodeBlob($outmd5_sql),
179 'math_html_conservativeness' => $this->conservativeness,
180 'math_html' => $this->html,
181 'math_mathml' => $this->mathml,
182 ), __METHOD__
183 );
184 }
185
186 // If we're replacing an older version of the image, make sure it's current.
187 global $wgUseSquid;
188 if ( $wgUseSquid ) {
189 $urls = array( $this->_mathImageUrl() );
190 $u = new SquidUpdate( $urls );
191 $u->doUpdate();
192 }
193 }
194
195 return $this->_doRender();
196 }
197
198 function _error( $msg, $append = '' ) {
199 $mf = htmlspecialchars( wfMsg( 'math_failure' ) );
200 $errmsg = htmlspecialchars( wfMsg( $msg ) );
201 $source = htmlspecialchars( str_replace( "\n", ' ', $this->tex ) );
202 return "<strong class='error'>$mf ($errmsg$append): $source</strong>\n";
203 }
204
205 function _recall() {
206 global $wgMathDirectory, $wgMathCheckFiles;
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 __METHOD__
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 }