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