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