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