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