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